Introduction
Here we have given an and all we have to do is shuffle the array. So the procedure is we have to separate the array in two parts from the middle and n is the middle point and the array is always have event number of index. Now we have to take element from the each array put it in serial. Like we have nums = [2,5,1,3,4,7], n = 3. Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Examples
Steps
- take a new array arr having same length of nums
- Run for loop, from 0 to n;
- Now in even position put, arr[2*i] = nums[i];
- In odd position, arr[2*i+i] = nums[n + i];
Java Code1:
class Solution {
public int[] shuffle(int[] nums, int n) {
int [] arr = new int[n*2];
for(int i = 0; i < n; i++){
arr[2*i] = nums[i];
arr[2*i + 1] = nums[n + i];
}
return arr;
}
}
Java Code2:
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] ans = new int[2*n];
int start = 1, end = n, i = 1;
ans[0] = nums[0];
while( i < 2*n){
if( i % 2 != 0) {
ans[i] = nums[end];
end++;
}
else{
ans[i] = nums[start];
start++;
}
i++;
}
return ans;
}
}
Top comments (0)