Processing math: 100%

Leetcode 1470 - Shuffle the Array

題目

Problem#

給你一個陣列 nums2n 個元素 [x1, x2, ..., xn, y1, y2, ..., yn]

要你回傳 [x1, y1, x2, y2, ..., xn, yn]

  • 測資限制:
    • 1n500
    • 1nums[i]103

想法#

直覺做法: 開陣列掃一次 0~n,依序 push nums[i]nums[n+i]
in-place: 因為不能開陣列,而且好像沒辦法 swap 的做完(至少我想不到),所以要想辦法把一半的數字先存起來,注意這題這題的值域最大 1000 而已,binary 只佔 10 個 bit,int 可以塞進三個,所以想法就是先把一半的數字 [0, n) encode 進另一半的數字 [n, 2*n)

  • 時間複雜度: O(n)
  • 空間複雜度: 直覺做法 O(n), in-place O(1)

AC Code#

  • 直覺做法
Copy
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> ans;
for(int i = 0; i < n; i++)
{
ans.push_back(nums[i]);
ans.push_back(nums[n+i]);
}
return ans;
}
};
view raw leetcode/1470.cpp delivered with ❤ by emgithub
  • in-place
Copy
class Solution2 {
public:
vector<int> shuffle(vector<int>& nums, int n) {
// encode 10bit
for(int i = n; i < 2*n; i++)
{
nums[i] = (nums[i]<<10) | nums[i-n];
}
const int mask = pow(2,10)-1;
for(int i = 0, j = n; i < 2*n && j < 2*n; )
{
nums[i] = nums[j] & mask;
nums[i+1] = nums[j] >> 10;
j++;
i += 2;
}
return nums;
}
};
view raw leetcode/1470.cpp delivered with ❤ by emgithub

心得#

in-place 作法看題解QAQ