40. The array of numbers appears only once (python)

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
Because the array of two numbers to occur only once, so that, after the figure is an exclusive OR, the result is that these two numbers XOR result, such as 1212345547 finish XOR 3 is the 111 ^ 7011 ^ 100 =
In the final result, from right to left to find the first occurrence of a 1 found in the third, the 100 taken out for each array and the number of the original operation, with the results obtained with the left and the right are both 0 the results obtained with the operation done is 1, so that you can find the two sub-arrays, according to which each of the two sub-array number of XOR, the two arrays is obtained
Appeared in a number of 3 and 7 magical
. 1  # - * - Coding: UTF-. 8 - * - 
2  class Solution:
 . 3      # return [a, b] where ab is a two numbers appear 
. 4      DEF FindNumsAppearOnce (Self, Array):
 . 5          # Write code here Wallpaper 
. 6          IF len (Array) <2 :
 . 7              return None
 . 8          tmpnum = None
 . 9          for NUM in Array:
 10              IF tmpnum == None:
 . 11                  tmpnum = NUM
 12 is              the else :
 13 is                  tmpnum ^ = NUM
14         count = 0
15         while tmpnum%2==0:
16             tmpnum = tmpnum >>1
17             count +=1
18         mask = 1 << count
19         firstNum = None
20         secondNum = None
21         for num in array:
22             if num&mask == 0:
23                 if firstNum == None:
24                     firstNum = num
25                 else:
26                     firstNum ^=num
27             else:
28                 if secondNum == None:
29                     secondNum = num
30                 else:
31                     secondNum ^= num
32         return firstNum,secondNum
33         

2019-12-23 14:58:21

Guess you like

Origin www.cnblogs.com/NPC-assange/p/12083797.html