题目地址:
https://leetcode.com/problems/shuffle-the-array/
给定一个长 2 n 2n 2n的数组 A = [ x 1 , x 2 , . . . , x n , y 1 , y 2 , . . . , y n ] A=[x_1,x_2,...,x_n,y_1,y_2,...,y_n] A=[x1,x2,...,xn,y1,y2,...,yn],要求返回 [ x 1 , y 1 , x 2 , y 2 , . . . , x n , y n ] [x_1,y_1,x_2,y_2,...,x_n,y_n] [x1,y1,x2,y2,...,xn,yn]。
代码如下:
public class Solution {
public int[] shuffle(int[] nums, int n) {
int idx1 = 0, idx2 = n;
int[] res = new int[nums.length];
// i每次向后走两格
for (int i = 0; i < res.length; i += 2) {
res[i] = nums[idx1++];
res[i + 1] = nums[idx2++];
}
return res;
}
}
时空复杂度 O ( n ) O(n) O(n)。