# Leetcode 1470. Shuffle the Array ## 僅供我自己學習紀錄 參考網路上的解答 因為題目要求的範圍遠小於2^16次方,而int可以儲存32 bits。 因此以下解法為讓一個nums[i]可以存放2個數字。 例如: x = 1 則 在16進位下表示為 0x00000001 y = 2 則 在16進位下表示為 0x00000002 若使 x 同時存放 x 與 y, 則可以視為x左移16 bits 也就是 x = 0x00010002 ```c++= class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { int endY = 2 * n - 1; int endX = n - 1; for (int i = endX, j = endY; i >= 0; i--, j--) { nums[i] <<= 0x10; // shl on 16 bits nums[i] |= nums[j]; } for (int i = endX, j = endY; i >= 0; i--, j -= 2) { nums[j] = nums[i] & 0xFFFF; // x & mask, where mask is 1111 1111 1111 1111 nums[j - 1] = nums[i] >> 0x10; // shr on 16 bits } return nums; } }; ``` # 我自己的想法(未AC) ![](https://i.imgur.com/VZrwpi2.png) ``` c++= class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { int temp[2] = { 0 }, swap = 0; for (int i = 0, k = n; i < 2*n; i += 2, k++) { if (i == 2 * n - 2)nums[i] = temp[1]; else if (i != 0)nums[i] = temp[0]; if (i + 1 < n)temp[0] = nums[i + 1]; nums[i + 1] = nums[k]; if (i + 2 < n)temp[1] = nums[i + 2]; } return nums; } }; ```