Solution 1
-
Use set to track all seen appeared numbers.
-
Remove seen number if it is re-visited.
-
The last one is the single number.
Space Complexity: O(n)
Solution 2 - Bitwise XOR
-
0 ^ N = N
andN ^ N = 0
-
So XOR all number together, only the single number’s value is preserved.
def singleNumber(self, nums):
for i in range(1,len(nums)):
nums[0] ^= nums[i]
return nums[0]