Numbers that appear only once in the sword index group

topic link

This is good to use twice, people remind people to use XOR to do it, what to do after XOR and sum, to separate these two numbers, only find one of the numbers and then XOR the other number to XOR , see the practice of others on Niuke.com, find out the bit whose XOR sum is 1 through bit operation, and then XOR all the numbers whose bit is 1 to find the number mentioned in the appeal. , It may be a bit confusing, but you should understand it by looking at the code.

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        int x = 0;
        if(data.size() < 2) {
            return ;
        }
        if(data.size() == 2) {
            *num1 = data[0];
            *num2 = data[1];
            return ;
        }
        for(int i = 0; i < (int)data.size(); i++) {
            x ^= data[i];
        }
        int index = findindex(x), y = 0;
        for(int i = 0; i < (int)data.size(); i++) {
            int time = index, num = data[i]; 
            while(time--) {
                num >>= 1;
            }
            if(num&1) {
                y ^= data[i];
            }
        }
        *num1 = y;
        *num2 = (x ^ y);
    }
    int findindex(int x) {
        int index = 0;
        while((x&1) == 0 && index < 32) {
            x >>= 1;
            index++;
        }
        return index;
    }
};

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326640703&siteId=291194637