这道题自己使用set实现的,也被ac了,发现太low了,后来发现别人写的就是棒
# -*- encoding = 'utf-8'-*-
__author__ = 'Administrator'
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
temp = set()
for i in range(len(nums)):
if nums[i] in temp:
temp.remove(nums[i])
else:
temp.add(nums[i])
# 将set中的元素放在列表中
res = [i for i in temp]
return res
def singleNumber2(self,nums):
xor = 0
for i in range(len(nums)):
xor ^= nums[i]
# 设两个单独的数是x y
# 此时得到的xor是x ^ y
# 获取最低位的1
# 例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码,two's complement)
# 则lowbit = 2(二进制:0010 xor & -xor)
lowbit = xor & -xor
# 通过lowbit可以将原有元素划分成lowbit = 1 和lowbit = 0两类
x = y = 0
for i in nums:
if i & lowbit:
x = x ^ i
else:
y = y ^ i
return [x,y]