哈希表,时间和空间复杂度都是O(n)
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Solution 1: 哈希表,时间和空间复杂度都是O(n)
hash_map = {}
for num in nums:
if hash_map.has_key(num):
# 在哈希表中,表示已经出现过一次,那么从哈希表中删除
hash_map.pop(num)
else:
# 不在哈希表中,添加到哈希表中
hash_map[num] = 1
# 哈希表中剩余两个数字
result = []
for key, _ in hash_map.items():
result.append(key)
return result
位运算
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Solution 2: 位运算
x = 0
for num in nums:
x = x ^ num
lowbit = x & (-x) # Note(1)
res1, res2 = 0, 0
for num in nums:
if num & lowbit: # Note(2)
res1 = res1 ^ num
else:
res2 = res2 ^ num
return [res1, res2]
Note:
(1)这里查找出res1和res2不同的位,res1和res2的lowbit分别是0和1,位运算太奇妙了,看不出来位置,也就是根据它做分类
(2)这里查找是在分类啊!太奇妙了~感觉炸裂
另一种位运算
参考题解:https://leetcode.cn/problems/single-number-iii/solutions/1073727/gong-shui-san-xie-yi-ti-shuang-jie-ha-xi-zgi4/