137. Single Number II
https://leetcode.com/problems/single-number-ii/
Python
Hash Set
class Solution:
def singleNumber(self, nums: List[int]) -> int:
m1, m2 = set(), set()
for num in nums:
if num not in m1:
m1.add(num)
continue
if num not in m2:
m2.add(num)
continue
m1.remove(num)
m2.remove(num)
return m1.pop()
Bit Manipulation
~
bitwise NOT^
xor
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ones, twos = 0, 0
for num in nums:
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
return ones