---
# System prepended metadata

title: 1470-Shuffle the Array
tags: [Easy]

---

# 1470-Shuffle the Array
###### tags: `Easy`
## Question
https://leetcode.com/problems/shuffle-the-array/
## Key
最快的方法是用一個array存
不過我的方法(用swap)最省空間
## Reference
## Solution
### My solution
```cpp=
class Solution {
public:
    void swap(vector<int>& nums, int a, int b)
    {
        nums[a] = nums[a]^nums[b];
        nums[b] = nums[a]^nums[b];
        nums[a] = nums[a]^nums[b];
    }
    vector<int> shuffle(vector<int>& nums, int n) {
        int j = n;
        int times = j-n+1;
        while(j < 2*n)
        {
            int i = j;
            while(i > times)
            {
                swap(nums, i, i-1);
                i--;
            }  
            times += 2;
            j++;
        }    
        return nums;
    }
};
```

### fastest solution
```cpp=
class Solution {
public:
    vector<int> shuffle(vector<int>& nums, int n) {
        vector<int> res;
        for (int i = 0, j = n; i < n; i++, j++)
        {
            res.push_back(nums[i]);
            res.push_back(nums[j]);
        }
        return res;
    }
};
```