LeetCode(Array)1929. Concatenation of Array
1.问题
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
Example 2:
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
Constraints:
- n == nums.length
- 1 <= n <= 1000
- 1 <= nums[i] <= 1000
2. 解题思路
方法1:
1.定义n为nums的长度,ans数组长度为2n
2.遍历数组,ans需要遍历两次nums数组的元素,第二次遍历的ans的索引值为i+n
3.返回ans
方法2:
1.定义n为nums的长度,ans数组长度为2n
2.System.arraycopy()的方法copy数组,copy两次
3.返回ans
3. 代码
代码1:
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;//1.定义n为nums的长度,ans数组长度为2n
int[] ans = new int[2*n];
for (int i = 0; i < n; i++) {
//2.遍历数组,ans需要遍历两次nums数组的元素,第二次遍历的ans的索引值为i+n
ans[i] = nums[i];
ans[i+n] = nums[i];
}
return ans;//3.返回ans
}
}
解题思路基本相同,代码1根据nums的索引遍历并存入ans,以下代码根据ans的索引长度遍历索引添加值。
class Solution {
public int[] getConcatenation(int[] nums) {
int[] ans = new int[2*nums.length];//1.定义ans数组长度为2*nnums.length
for (int i = 0; i < 2*nums.length; i++) {
//2.遍历数组,nums的索引除以本身数组长度,nums的索引下标值添加到ans数组里
ans[i] = nums[i%nums.length];
}
return ans;//3.返回ans
}
}
代码2:
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;//1.定义n为nums的长度,ans数组长度为2n
int[] ans = new int[2*n];
System.arraycopy(nums,0,ans,0,n);//2.System.arraycopy()的方法copy数组,copy两次
System.arraycopy(nums,0,ans,n,n);
return ans;//3.返回ans
}
}
还没有评论,来说两句吧...