Bit in place
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
"""tc O(N) sc O(1)
main idea: bit manipulation + pair value in place overlap
since nums[i] range [1,1000] => only occupy 10bits, we can use the feature a int number has 32 bits length to save its paired number's value by left shift 10 bits forward
1. loop first half, save left half number onto its pair by left shift
2. start with right half, get xi,yi and assign them to A[i],A[i+1] seperately
3. move i by 2 steps
4. keep doing it until step2 is over
"""
for l in range(n-1,-1,-1):
r = l+n
nums[r] <<= 10 #10N
nums[r] |= nums[l] #10N
i = 0
for r in range(n,len(nums)):
x1 = nums[r] & 1023 #10N
y1 = nums[r] >> 10 #10N
nums[i] = x1
nums[i+1] = y1
i += 2
return nums
What if range of each element is bigger???? use -1 to mark
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
"""
(assuming numbers are all positive )
main idea: loop all nums and swap each x into correspoinding position and mark as negtive
3. for the item was in position i, we recursively put it into desired place as well until "be-swapped unwillingly" items are in desired position
4. keep doing the loop until finish
5. revert all neg number back to pos
"""
def get_other_idx(i):
if i < n :
return 2*i
else:
return 2*(i-n)+1
for i in range(2*n):
print(f"before i is {i}")
j = i # cache index
while nums[i] > 0: # i: reluctent swaped index
j = get_other_idx(j)
nums[i],nums[j] = nums[j],-nums[i]
for i in range(2*n):
nums[i] = -nums[i]
return nums