Sponsored
Sponsored
This approach uses a two-pointer technique to shuffle the array. The first pointer starts at the beginning of the array and represents the x values. The second pointer starts at the middle of the array and represents the y values. By iterating over the array and adding elements from these two pointers alternately to a new list, we can achieve the desired shuffle.
Time Complexity: O(n), where n is half the length of the array. We iterate through the array once.
Space Complexity: O(n), for storing the shuffled result.
1#include <iostream>
2#include <vector>
3
4std::vector<int> shuffle(const std::vector<int>& nums, int n) {
5 std::vector<int> result;
6 for (int i = 0; i < n; ++i) {
7 result.push_back(nums[i]);
8 result.push_back(nums[i + n]);
9 }
10 return result;
11}
12
13int main() {
14 std::vector<int> nums = {2, 5, 1, 3, 4, 7};
15 int n = 3;
16 std::vector<int> result = shuffle(nums, n);
17 for (int num : result) {
18 std::cout << num << " ";
19 }
20 return 0;
21}
In this C++ solution, we define a shuffle function that returns a vector with the shuffled values using the two-pointer technique. The result is then printed in the main function.
An alternate approach is to reorder the array in-place without using additional space. However, given the elements might need to be accessed multiple times, a good understanding of index manipulation and mathematics is required. The complexity to deduce the correct indices for swapping can increase the difficulty.
Time Complexity: O(n^2) in the worst case as the array is shifted multiple times.
Space Complexity: O(1), as the shuffling is done in-place.
1
class Program {
static void ShuffleInPlace(int[] nums, int n) {
for (int i = n; i < 2 * n; i++) {
int y = nums[i];
for (int j = i; j > 2 * (i - n); j--) {
nums[j] = nums[j - 1];
}
nums[2 * (i - n)] = y;
}
}
static void Main() {
int[] nums = {2, 5, 1, 3, 4, 7};
int n = 3;
ShuffleInPlace(nums, n);
Console.WriteLine(string.Join(", ", nums));
}
}
In the C# solution, we shuffle the input array in place by assigning elements through systematic index shifts, avoiding extra space use.