面試題56 - I. 數組中數字出現的次數(位操作的精妙不太懂)

一個整型數組 nums 裏除兩個數字之外,其他數字都出現了兩次。請寫程序找出這兩個只出現一次的數字。要求時間複雜度是O(n),空間複雜度是O(1)。

hashmap(字典實現)

此解法空間複雜度爲O(n)

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        dic = {}
        for i in nums:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        res=[]
        for i,j in dic.items():
            if j == 1:
                res.append(i)
        return res

位操作(很巧妙,不太懂)

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        ret = 0  # 所有數字異或的結果
        a = 0
        b = 0
        for n in nums:
            ret ^= n
        # 找到第一位不是0的
        h = 1
        while(ret & h == 0):
            h <<= 1
        for n in nums:
            # 根據該位是否爲0將其分爲兩組
            if (h & n == 0):
                a ^= n
            else:
                b ^= n

        return [a, b]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章