Cattle off network topic - array of numbers only appear once

Title described as follows:

In addition to an array of integers in two numbers, the other numbers appear twice. Please write program to find these two numbers appear only once

The main idea of ​​the solution to a problem

  1. Exclusive OR operation, two identical numbers, exclusive-OR operation results obtained as 0, if the array only once a number of occurrences, the other numbers are present twice,
    according to the exclusive-OR operation principle, all numbers may be exclusive or array, it can find, this appears only once digital

  2. If the two numbers appear only once array, the array may be divided into two groups, each group containing only a number appears only once. How will such an array is divided into sub-arrays?
    All the numbers in the array results are certainly not exclusive OR 0, this number may be extracted from a bit equal to 1, the array can be divided into an array of all, with this bit is 1, and not
    two 1's, so that each XOR group, the corresponding number can be obtained.

code show as below:

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
         int len = data.size(); 
        if( len < 2 ){
            return ;
        }
        
        int k = 0;
        for(int i=0;i<len; i++){
            k ^= data[i];
        }
        
        int index = fisrtIndexOf1(k);
        *num1 = *num2 = 0;
         for(int i=0; i<len ; i++){
             if((data[i] >> index)&0x1){
                 *num1 ^= data[i]; 
             }else {
                 *num2 ^= data[i];
             }
             
         }
        
    }
    
    
    int fisrtIndexOf1(int num){
       
        int index = 0;
        while( num  ){
            if(num &(0x1))
                return index;
            
             num = num>>1;
             ++index;
        }
        return -1;
    }
    
    
};






Guess you like

Origin www.cnblogs.com/wanshuafe/p/11768985.html