LeetcodeMedium-【面試題56 - I. 數組中數字出現的次數】*

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

示例 1:
輸入:nums = [4,1,4,6]
輸出:[1,6] 或 [6,1]

示例 2:
輸入:nums = [1,2,10,4,1,4,3,3]
輸出:[2,10] 或 [10,2]

限制:
2 <= nums.length <= 10000

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路1:異或

視頻講解
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        ret = 0
        # 全員異或
        for n in nums:
            ret ^= n
        # 找到第一個非零值
        h = 1
        while (h&ret) == 0:
            h <<= 1
        # 分組異或
        a = 0
        b = 0
        for n in nums:
            if (n&h) != 0:
                a ^= n
            else:
                b ^= n 
        return [a, b]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章