[Leetcode][python3]Day01.Single Number (30-Day LeetCoding Challenge)

30 days! Lets go Lets go!
N2I -2020.04.01

1. My Solution

  1. class Solution:
  2. def singleNumber(self, nums) -> int:
  3. dic={}
  4. for i in nums:
  5. if i in dic:
  6. del dic[i]
  7. else:
  8. dic[i]=1
  9. for res,tmp in dic.items():
  10. return res

2. A better Solution

  1. class Solution:
  2. def singleNumber(self, nums: List[int]) -> int:
  3. count = 0
  4. for num in nums:
  5. count ^= num
  6. print(count)
  7. return count

Explanation:

This solution using XOR to solve the problem. It is the best way which is fast and using only one extra memory.