Topic
number of falling orders III
The number of 2*n + 2 is given, except two of which each number appears two times, and the two numbers are found.
Sample Example
Given [1,2,2,3,4,4,5,3], return 1 and 5
challenges
O (n) time complexity, O (1) Additional space complexity
Solving
According to the number I, it can be thought that all the number of different or run results is the two number of different or result.
This XOR result, where the binary number is 1, indicates that these two numbers correspond to bits. And then how to restore???
Reference, understood not very thoroughly, after finding the K-bit, and then judging the array so that the number of K-bit is 0 or 1, two times the number of the solution has no effect, through this k for the array into two categories, also the two numbers are separated, here the K bit in a, B must be different, must be a 1 1.
Public classSolution {/** * @paramA:an Integer Array *@return: Integers*/ PublicList<integer> SINGLENUMBERIII (int[] A) {//Write your code here intAxorb = 0; LinkedList<Integer> res =NewLinkedlist<integer>(); for(inti = 0; I <a.length;i++) {Axorb^=A[i]; } intA = 0; intb = 0; intK = 0; while(Axorb% 2==0) {Axorb>>= 1; K++; } for(inti=0;i< a.length;i++){ intTMP = (a[i]>>k)%2; if(tmp==0) A^=A[i]; Elseb^=A[i]; } res.add (a); Res.add (b); returnRes; }}
Java Code
Total time: 3520 Ms
classSolution:"""@param a:an integer array @return:""" defsinglenumberiii (Self, A):#Write your code herex =0 forNumincha:x^=Num a=0 B=0 K=0 whilex%2==0:x= X>>1k+=1 forNumincha:tmp= (num>>k)%2iftmp==0:a^=NumElse: b^=Numreturn[A, b]
Python Code
Total time: 514 Ms
Of course, for such a topic, the use of HashMap is the simplest.
Public classSolution {/** * @paramA:an Integer Array *@return: Integers*/ PublicList<integer> SINGLENUMBERIII (int[] A) {//Write your code herehashmap<integer,integer> map =NewHashmap<integer,integer>(); LinkedList<Integer> res =NewLinkedlist<integer>(); for(inti=0;i<a.length;i++){ if(Map.containskey (A[i])) {Map.put (A[i],map.get (a[i) )-W); }Else{map.put (a[i],1); } if(Map.get (A[i]) ==2) Map.Remove (A[i]); } for(Integer k:map.keyset ()) {res.add (k); } returnRes; }}
Java Code
Total time: 4318 ms
Optimize for a bit
Public classSolution {/** * @paramA:an Integer Array *@return: Integers*/ PublicList<integer> SINGLENUMBERIII (int[] A) {//Write your code herehashmap<integer,integer> map =NewHashmap<integer,integer>(); LinkedList<Integer> res =NewLinkedlist<integer>(); for(inti=0;i<a.length;i++){ if(Map.containskey (A[i])) {Map.Remove (a[i]); }Else{map.put (a[i],1); } } for(Integer k:map.keyset ()) {res.add (k); } returnRes; }}
Java Code
Total time: 3995 Ms
classSolution:"""@param a:an integer array @return:""" defsinglenumberiii (Self, A):#Write your code hereD = {} forNuminchA:ifNuminchD:delD[num]Else: D[num]= 1returnD.keys ()
Python Code
Total time: 586 ms
Lintcode Medium Title: Number III of single numbers III