Bit operation 73. Two numbers that appear only once in the array

topic

Topic link: 73. Two numbers that only appear once in the array

answer

The idea is to split the question into two simple sub-questions: find a number that appears once in an array.

We need to use a property of XOR operation: xxx ^ x = 0 x = 0 x=0 .
Meaning of the questions, in addition to the two figures are askingxxxyyy , the rest of the numbers appear twice or more, then the number we get after XOR all the numbers is the desiredxxxyyXOR of y .

Since x ≠ yx \neq yx=y , so the result must not be equal to 0, that is, there must be at least one bit that is not 0 after converting it to binary.

Find the position of a bit that is not 0, and divide the given array into two arrays: a number with 1 and a number with 0.

x x xyyy must be located in a different array. The same number must be in the same array.

At this point, the problem has been transformed into: a number that only appears once in the array.
XOR one of the arrays and the result is xxxyyy .
The corresponding other number can be compared with the previousxxxyyThe XOR value of y is XORed. Thatxxx ^ x x x ^y = yy = yY=and .

AC code

class Solution {
public:
    vector<int> findNumsAppearOnce(vector<int>& nums) {
        int sum = 0;
        for (auto i : nums) sum ^= i;
        int k = 0;
        while (true) {
            if (!(sum & (1 << k))) k++;
            else break;
        }
        int x = 0;
        for (auto i : nums) {
            if ((1<<k) & i) x ^= i;
        }
        return vector<int> {x, x ^ sum};
    }
};

Guess you like

Origin blog.csdn.net/qq_45934120/article/details/107987099