Title Description
In addition to an array of integers in two numbers, the other numbers appear twice. Please write a program to find these two figures appear only.
Thinking
The question I was going to use violence to solve, get a dictionary, then counts each number.
optimization
Space complexity is O (1)
With XOR, the same number of XOR is XOR 0,0 any number of any number.
So that all or a number of different results for the two numbers appear only once
Then according to the XOR result, the number of bits to identify two different one (just need to find a like)
According to this bit packets, a group is 0, 1, as a group. In this way the two figures must have been assigned to different groups. The inside of each set of numbers, only a few appear only once, and the remaining number appeared twice ..... needless to say, were XOR
class Solution:
def FindNumsAppearOnce(self, array):
if len(array)<2:
return False
num = array[0] ^ array[1]
for i in range(2,len(array)):
num ^= array[i]
# 找到二进制位不同的一位,只需要找出来一位就行
i = 1
while num%2 == 0:
num = int(num//2)
i += 1
# 按照上面找到的二进制位分组异或
num1 = 0
num2 = 0
for num in array:
if num%(2**i) == (2**(i-1)):
num1 ^= num
else:
num2 ^= num
return num1,num2