『哈希表;位運算』只出現一次的數字136

題目相關

題目解讀

顯而易見,一個字典即可搞定。然而此題還有一種相當巧妙的解法是位運算,具體如:

  • 如果我們對 0 和二進制位做 XOR 運算,得到的仍然是這個二進制位
    a \oplus 0 = a
  • 如果我們對相同的二進制位做 XOR 運算,返回的結果是 0
    a \oplus a = 0
  • XOR 滿足交換律和結合律
    a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = b

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章