Guest User

main.py

a guest
Jul 8th, 2023
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # O(n) time, O(1) space
  4.  
  5. # [1, 2, 1, 2, 3, 4, 4] -> 3
  6. def single_number_twice(nums):
  7.     s = 0
  8.     for num in nums:
  9.         s ^= num
  10.     return s
  11.  
  12. # [1, 2, 1, 2, 3, 4, 4, 1, 2, 4] -> 3
  13. def single_number_thrice(nums):
  14.     # 1st, 4th, 7th...
  15.     ones = 0
  16.     # 2nd, 5th, 8th...
  17.     twos = 0
  18.     # "Disable" the 3rd time bits
  19.     common = 0
  20.     for num in nums:
  21.         twos |= num & ones
  22.         ones ^= num
  23.         # ones & twos - bits that we saw 3 times, so we get the OPPOSITE mask.
  24.         common = ~(ones & twos)
  25.         # Turn off those bits.
  26.         ones &= common
  27.         twos &= common
  28.     return ones
  29.  
  30. # [1, 2, 1, 2, 3, 4, 4, 5] -> [3, 5] / [5, 3]
  31. def duo_twice(nums):
  32.     s = 0
  33.     for num in nums:
  34.         s ^= num # 3 ^ 5
  35.     s &= -s
  36.     s_on = 0
  37.     s_off = 0
  38.     for num in nums:
  39.         if num & s:
  40.             s_on ^= num
  41.         else:
  42.             s_off ^= num
  43.     return [s_on, s_off]
  44.  
  45. print(duo_twice([1, 2, 1, 2, 3, 4, 4, 5]))
Advertisement
Add Comment
Please, Sign In to add comment