The problem is to rearrange the array by interleaving the first n and last n elements. We can do this by iterating through both halves and picking one from each alternately.
classSolution {
publicint[]shuffle(int[] nums, int n) {
int[] ans =newint[2*n];
for (int i = 0; i < n; i++) {
ans[2*i]= nums[i];
ans[2*i+1]= nums[i+n];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funshuffle(nums: IntArray, n: Int): IntArray {
val ans = IntArray(2*n)
for (i in0 until n) {
ans[2*i] = nums[i]
ans[2*i+1] = nums[i+n]
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
defshuffle(self, nums: list[int], n: int) -> list[int]:
ans = [0]*(2*n)
for i in range(n):
ans[2*i] = nums[i]
ans[2*i+1] = nums[i+n]
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnshuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
let n = n asusize;
letmut ans =vec![0; 2*n];
for i in0..n {
ans[2*i] = nums[i];
ans[2*i+1] = nums[i+n];
}
ans
}
}