一個整型數組 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]