題目相關
- 原題鏈接:136. 只出現一次的數字 - 力扣(LeetCode)
- 涉及知識:哈希表,位運算
- 題目難度:★
題目解讀
顯而易見,一個字典即可搞定。然而此題還有一種相當巧妙的解法是位運算,具體如:
- 如果我們對 0 和二進制位做 XOR 運算,得到的仍然是這個二進制位
- 如果我們對相同的二進制位做 XOR 運算,返回的結果是 0
- XOR 滿足交換律和結合律
Python相關
無
具體實現
哈希表實現如下:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
dic = {}
for num in nums:
if num not in dic:
dic[num] = 1
else:
del dic[num]
return list(dic.keys())[0]
位運算實現如下:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a