Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # O(n) time, O(1) space
- # [1, 2, 1, 2, 3, 4, 4] -> 3
- def single_number_twice(nums):
- s = 0
- for num in nums:
- s ^= num
- return s
- # [1, 2, 1, 2, 3, 4, 4, 1, 2, 4] -> 3
- def single_number_thrice(nums):
- # 1st, 4th, 7th...
- ones = 0
- # 2nd, 5th, 8th...
- twos = 0
- # "Disable" the 3rd time bits
- common = 0
- for num in nums:
- twos |= num & ones
- ones ^= num
- # ones & twos - bits that we saw 3 times, so we get the OPPOSITE mask.
- common = ~(ones & twos)
- # Turn off those bits.
- ones &= common
- twos &= common
- return ones
- # [1, 2, 1, 2, 3, 4, 4, 5] -> [3, 5] / [5, 3]
- def duo_twice(nums):
- s = 0
- for num in nums:
- s ^= num # 3 ^ 5
- s &= -s
- s_on = 0
- s_off = 0
- for num in nums:
- if num & s:
- s_on ^= num
- else:
- s_off ^= num
- return [s_on, s_off]
- print(duo_twice([1, 2, 1, 2, 3, 4, 4, 5]))
Advertisement
Add Comment
Please, Sign In to add comment