73. The array of two numbers appear only once

 

 

XOR see the video of it. AcWing 73. array of two numbers appear only once

https://www.acwing.com/solution/acwing/content/1324/

It is assumed that the number of 2 x, y

1. The exclusive-or of all numbers, the same number 2 after the exclusive OR is 0. The result is x⊕y.

2. The nature of the exclusive-OR operation: If a is the binary number 0101, b is the binary number 1011; the a⊕b = 1110, only two bits are not simultaneously comparison result 1, result is 0 otherwise.

To be sure, the results are a bit x⊕y k is 1. Using the k-th bit is 1, the array is divided into 2 categories array, the array is m Z = 1, n is other array Z = 0.

x and y are in m, n in.

3. m, n respectively in exclusive or elements can be obtained x, y.

 

class Solution {
public:
    Vector < int > findNumsAppearOnce (Vector < int > & the nums) {
         int SUM = 0 ;
         for (Auto X: the nums) SUM ^ = X;
         int K = 0 ;
         the while ((SUM >> K &! . 1 )) K ++;   // K is stored in the x or y in a different one who is 1 
        int First = 0 ;
         for (x Auto: the nums)
             IF (x & K >> 1 )
                First ^ = x; // be the first k bits of a set of exclusive-OR, to obtain a first number x of time appears 
        return Vector < int > {First, First SUM ^}; // SUM ^ First, to obtain a second occurrence number Y 
    }

};

 

Guess you like

Origin www.cnblogs.com/make-big-money/p/12339887.html