Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
很有意思的bit manipulation的题目。
&,位与运算,能确定两个数字的所有二进制下1的位置。
|, 位或运算,能确定两个数字的所有二进制下0的位置。
^,异或运算,能确定两个数字的所有二进制下不同value的位置。
解题思路:
1. 对list进行异或处理,得到的结果应该就是唯二的两个出现了一次的数字的异或的值。
2. 对于得到的值,value是1的位置,就是两个数字value不同的位置。
for num in nums:
xor ^= num # 得到两个数字的异或结果
3. 新建一个mask,mask=1,把1的位置移到右起第一个异或结果数值是1的位置。
mask = 1
while mask & xor == 0:
mask <<= 1 # 循环得到第一个异或结果为1的位置
4. 然后循环list,每一个数字都和mask进行于&运算。
5. 位置是1的是一个group,位置是0的是一个group。当然的,需要的两个结果会在不同的group里面,因为那个位置是异或为1的位置。
6. 然后每个num再和0进行异或运算,重复的出现两次的值会归0.剩下的就是我们需要的结果。
for num in nums:
if num & mask: # group 1
a ^= num
else: # group 0
b ^= num
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
a, b = 0, 0
for num in nums:
xor ^= num
mask = 1
while mask & xor == 0:
mask <<= 1
for num in nums:
if num & mask:
a ^= num
else:
b ^= num
return [a, b]
===================
二进制 -》 十进制
int('10100111110',2) # 1342
二进制 -》 十六进制
hex(int('101010',2)) # 0x2a
八进制 -》 二进制
bin(int('17',8)) # 0b1111
十进制 -》 二进制
bin(10) # 0b1010