依然还是用熟悉的python写的
问题描述:
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?
很有意思的一道题,因为之前写过single number I,所以这次看到这道题就进来了,刚开始的思路肯定是任意两个相同数的亦或为0,但是这道题有两个single number,假设为a、b,遍历亦或的结果是a^b,没法分别a、b。想了挺久还是没什么思路,后来想过用hash来做,取一个很大很大的hash值x,保证任意数hash x都是它自己,最后取只有一个的hash桶,但这样做的空间复杂度太高。没办法,只能去偷窥答案,发现是实在机智:思路依然是任意两个相同数的亦或为0,那么现在的任务就是把nums分成两段,其中每一段只含有一个single number。how?假设d=a^b,因为a、b是两个不同的值所以d的二进制表示至少有一位是1,同时,a、b在该位上分别为0和1,那么好了,以此作为分别标志,将nums分成两段,分别循环亦或,最后得到的值就是两个singlenumber
代码:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
d = 0
for i in nums:
d ^= i
d &= -d #找到最低非1位,负数以补码形式存储
r = [0,0]
for i in nums:
if (d&i)==0:
r[0] ^= i
else:
r[1] ^= i
return r
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
d = 0
for i in nums:
d ^= i
d &= -d #找到最低非1位,负数以补码形式存储
r = [0,0]
for i in nums:
if (d&i)==0:
r[0] ^= i
else:
r[1] ^= i
return r