1470. Rearrange the array (C++)
1 topic description
Give you an array nums, there are 2n elements in the array, arranged in the format [x1,x2,...,xn,y1,y2,...,yn].
Please rearrange the array in the format [x1,y1,x2,y2,…,xn,yn] and return the rearranged array.
2 Example description
2.1 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, so the answer is [2,3,5,4,1,7]
2.2 Example 2
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
2.3 Example 3
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
3 Problem solving tips
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
4 Detailed source code (C++)
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> res;
int j = 0 , k = 0;
for (int i = 0 ; i < nums.size() ; i++)
{
if (i % 2 == 0)
{
res.push_back(nums[k]);
k ++;
}
else
{
j ++;
res.push_back(nums[n+j-1]);
}
}
return res;
}
};