Shuffle the Array Solutions in C++
Number 1470
Difficulty Easy
Acceptance 88.9%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/shuffle-the-array/// Author : Hao Chen// Date : 2020-10-02class Solution {public:vector<int> shuffle(vector<int>& nums, int n) {vector<int> result;for (int i=0; i<n; i++) {result.push_back(nums[i]);result.push_back(nums[i+n]);}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/shuffle-the-array//// Author : liuyubobobo/// Time : 2020-06-06#include <iostream>#include <vector>using namespace std;/// Simulation/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:vector<int> shuffle(vector<int>& nums, int n) {vector<int> res(2 * n);for(int i = 0, j = 0; i < n; i ++)res[j ++] = nums[i], res[j ++] = nums[n + i];return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/shuffle-the-array//// Author : liuyubobobo/// Time : 2020-06-08#include <iostream>#include <vector>using namespace std;/// Using the higher bits to store the numbers/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<int> shuffle(vector<int>& nums, int n) {for(int i = 0; i < 2 * n; i ++){int j = i < n ? 2 * i : 2 * (i - n) + 1;nums[j] |= (nums[i] & 1023) << 10;}for(int& e: nums) e >>= 10;return nums;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/shuffle-the-array//// Author : liuyubobobo/// Time : 2020-06-08#include <iostream>#include <vector>using namespace std;/// Using nums[i] as a buffer storage/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<int> shuffle(vector<int>& nums, int n) {for(int i = 0; i < 2 * n; i ++)if(nums[i] > 0){int j = i;while(nums[i] > 0){j = j < n ? 2 * j : 2 * (j - n) + 1;swap(nums[i], nums[j]);nums[j] = -nums[j];}}for(int& e: nums) e = -e;return nums;}};int main() {return 0;}