題目相關(guān)
- 原題鏈接:136. 只出現(xiàn)一次的數(shù)字 - 力扣(LeetCode)
- 涉及知識(shí):哈希表,位運(yùn)算
- 題目難度:★
題目解讀
顯而易見(jiàn),一個(gè)字典即可搞定。然而此題還有一種相當(dāng)巧妙的解法是位運(yùn)算,具體如:
- 如果我們對(duì) 0 和二進(jìn)制位做 XOR 運(yùn)算,得到的仍然是這個(gè)二進(jìn)制位
- 如果我們對(duì)相同的二進(jìn)制位做 XOR 運(yùn)算,返回的結(jié)果是 0
- XOR 滿足交換律和結(jié)合律
Python相關(guān)
無(wú)
具體實(shí)現(xiàn)
哈希表實(shí)現(xiàn)如下:
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]
位運(yùn)算實(shí)現(xiàn)如下:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a