Skip to content

Commit 2ca73e5

Browse files
committed
Update single-number-iii.cpp
1 parent 3491499 commit 2ca73e5

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

C++/single-number-iii.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,25 @@
22
// Space: O(1)
33

44
class Solution {
5+
public:
6+
vector<int> singleNumber(vector<int>& nums) {
7+
// Xor all the elements to get x ^ y.
8+
int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor<int>());
9+
// Get the last bit where 1 occurs.
10+
x_xor_y &= -x_xor_y;
11+
12+
// Get the subset of A where the number has the bit.
13+
// The subset only contains one of the two integers, call it x.
14+
// Xor all the elemets in the subset to get x.
15+
vector<int> result(2, 0);
16+
for (const auto& i : nums) {
17+
result[!(i & x_xor_y)] ^= i;
18+
}
19+
return result;
20+
}
21+
};
22+
23+
class Solution2 {
524
public:
625
vector<int> singleNumber(vector<int>& nums) {
726
// Xor all the elements to get x ^ y.

0 commit comments

Comments
 (0)