Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #bit counting at every position and consider those bits whose count%3==1 because if the number occured once then either a bit at any position can be 1 or 4(if all elements have also that bit)
- #T.C=32*n n=total number of elements for each element.
- class Solution:
- def singleNumber(self, nums: List[int]) -> int:
- result = 0
- for bit in range(32):
- count = 0
- for num in nums:
- if (num >> bit) & 1:
- count += 1
- if count % 3 != 0: #Right shift 'num' by 'bit' positions will make that bit at 1st place from right Then AND with 1 to check if that bit is set (1) or not (0)
- result |= (1 << bit) # if set then do or in the result at that position.
- # handle negative number (32-bit signed)
- if result >= 2**31:
- result -= 2**32
- return result
- #Time complexity O(n), no space used
- class Solution:
- def singleNumber(self, nums: List[int]) -> int:
- ones=0 #it will store only those elements which occurs once but not third time element
- twos=0 #it will store only those elements which occurs twice
- for i in nums:
- ones= (ones^i) & ~twos
- twos=(twos^i) & ~ones
- return ones #finally ones will have a element which will have the frequency of 1
Advertisement
Add Comment
Please, Sign In to add comment