LeetCode(Array)1470. Shuffle the Array
1.问题
Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn].
Return the array in the form [x1,y1,x2,y2,…,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
- 1 <= n <= 500
- nums.length == 2n
- 1 <= nums[i] <= 10^3
2. 解题思路
方法1:
1.定义result数组,长度为2n
2.n之前的元素遍历循环插入数组,n之后的元素遍历循环插入数组,rsult的索引遍历循环加1
3.返回reuslt
方法2:
1.定义result数组,长度为2n
2.遍历数组,长度小于n,2i和2i+1是result遍历后的索引,nums[i]和nums[n+i]是对应的值
3.返回result
方法3:
1.定义result数组,长度为2n
2.索引i为0,left索引的0,right的索引为n
3.如果left小于n,nums[left++]和nums[right++]添加到result数组中
4.返回result
3. 代码
代码1:
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] result = new int[2 * n];//1.定义result数组,长度为2n
for (int i = 0, j = n, idx = 0; idx < result.length; i++, j++) {
//2.n之前的元素遍历循环插入数组,n之后的元素遍历循环插入数组,rsult的索引遍历循环加1
result[idx++] = nums[i];
result[idx++] = nums[j];
}
return result;//3.返回reuslt
}
}
以下代码虽然运行没有问题,但时间复杂度较高,不推荐
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] result = new int[nums.length];
int[] x = new int[n];
int[] y = new int[n];
System.arraycopy(nums,0,x,0,n);
System.arraycopy(nums,n,y,0,n);
List list = new ArrayList<Integer>();
for(int i=0;i<n;i++){
list.add(x[i]);
list.add(y[i]);
}
for(int j=0;j<nums.length;j++){
result[j]= (int) list.get(j);
}
return result;
}
}
代码2:
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] result = new int[2*n];//1.定义result数组,长度为2n
for(int i = 0; i < n; i++){
//2.遍历数组,长度小于n,2*i和2*i+1是result遍历后的索引,nums[i]和nums[n+i]是对应的值
result[2 * i] = nums[i];
result[2 * i + 1] = nums[n+i];
}
return result;//3.返回result
}
}
代码3:
class Solution {
public int[] shuffle(int[] nums, int n) {
int [] result = new int[2*n];//1.定义result数组,长度为2n
int i = 0;//索引i为0,left索引的0,right的索引为n
int left = 0;
int right = n;
while(left < n){
//3.如果left小于n,nums[left++]和nums[right++]添加到result数组中
result[i++] = nums[left++];
result[i++] = nums[right++];
}
return result;
}
}
还没有评论,来说两句吧...