../ Competitive Programming
-rw-r--r--aguang1.1 KiB1 min read

Leet Code Daily 2024-05-31 - Single Number III

Solution

Let's say xx and yy are the numbers we are looking for.

We know:

x⊕y=⊕i=0n−1Aix \oplus y = \oplus_{i = 0}^{n - 1} A_i

There is at least one bit diffecnce between xx and yy. If we split numbers into two buckets by that bit and perform, xx and yy will be put into diffrent buckets.

And then we can just perform XOR sum again.

Code

c++
class Solution {
public:
    int computeXOR(vector<int>& nums) {
        int ret = 0;
        for (const auto& x : nums) {
            ret = ret ^ x;
        }
        return ret;
    }

    vector<int> singleNumber(vector<int>& nums) {
        int t = computeXOR(nums);
        vector<int> buckets[2];
        for (int mask = 1;; mask <<= 1) {
            if (mask & t) {
                for (const auto& x : nums) {
                    buckets[(mask & x) ? 1 : 0].push_back(x);
                }
                break;
            }
        }
        return vector<int>{computeXOR(buckets[0]), computeXOR(buckets[1])};
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window