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.
Example:
Input:[1,2,1,3,2,5]
Output:[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?
LeetCode:链接
剑指offer同题:链接剑指Offer_编程题40:数组中只出现一次的数字(异或)
我们还是从头到尾一次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数组的异或结果。因为其他数字都出现了两次,在异或中全部抵消了。由于两个数字肯定不一样,那么异或的结果肯定不为0,也就是说这个结果数组的二进制表示至少有一个位为1。我们在结果数组中找到第一个为1的位的位置,记为第n位。现在我们以第n位是不是1为标准把元数组中的数字分成两个子数组,第一个子数组中每个数字的第n位都是1,而第二个子数组中每个数字的第n位都是0。
A和0异或的结果还是A。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
remain, index = 0, 1
'''得到A和B异或的结果'''
for num in nums:
remain ^= num
'''根据异或的结果找到从右往左的第一个1'''
while remain & index == 0:
index = index << 1
remain1, remain2 = 0, 0
'''分组判断 必须判断是否为0'''
for num in nums:
if num & index == 0:
remain1 ^= num
else:
remain2 ^= num
return [remain1, remain2]