Leetcode 1470. Shuffle the Array
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:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
2n
elements.x
and y
in the array?
x
and y
are integers and are within the bounds given by the problem constraints.#include <vector>
#include <iostream>
using namespace std;
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> result(2 * n); // Initialize result array with size 2n
for (int i = 0; i < n; ++i) {
result[2 * i] = nums[i]; // Add element from the first half
result[2 * i + 1] = nums[n + i]; // Add element from the second half
}
return result;
}
// Driver code to test the function
int main() {
vector<int> nums1 = {2, 5, 1, 3, 4, 7};
int n1 = 3;
vector<int> result1 = shuffle(nums1, n1);
for (int num : result1) {
cout << num << " ";
}
cout << endl;
vector<int> nums2 = {1, 2, 3, 4, 4, 3, 2, 1};
int n2 = 4;
vector<int> result2 = shuffle(nums2, n2);
for (int num : result2) {
cout << num << " ";
}
cout << endl;
return 0;
}
n
is the half-length of the array nums
(or alternatively, 2n
operations for an array of size 2n
).2n
.By following this strategy, we can efficiently shuffle the array as required by the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?