哈希表法:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
visited = {}
for num in nums:
try:
visited.pop(num)
except:
visited[num] = '1'
return visited.popitem()[0]
数学法:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return 2 * sum(set(nums)) - sum(nums)
位运算法:
,
,
。
:表示异或
因此只需要一直执行异或运算即可:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result