Description Link to heading
260. Single Number III (Medium)
Given an integer array nums
, in which exactly two elements appear only once and all the other
elements appear exactly twice. Find the two elements that appear only once. You can return the
answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Example 1:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
Example 2:
Input: nums = [-1,0]
Output: [-1,0]
Example 3:
Input: nums = [0,1]
Output: [1,0]
Constraints:
2 <= nums.length <= 3 * 10⁴
-2³¹ <= nums[i] <= 2³¹ - 1
- Each integer in
nums
will appear twice, only two integers will appear once.
Solution Link to heading
Initially, perform bitwise XOR on all numbers. Assuming the elements to be identified are denoted as $a$ and $b$, the result of the XOR operation is $c = a \oplus b$. Consider obtaining the lowbit of $c$, which is $c & (-c)$. This enables us to categorize all elements into two groups: one with $nums[i] & lowbit = 0$ and the other with non-zero values. Notably, $a$ and $b$ each belong to one of these groups. If the XOR result of all elements in the first group is $a$, then the XOR result of all elements in the second group is $b$.
Code Link to heading
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
long res = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
res = res ^ nums[i];
}
long c = (res & (-res));
int res1 = 0, res2 = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] & c) {
res1 = res1 ^ nums[i];
} else {
res2 = res2 ^ nums[i];
}
}
return {res1, res2};
}
};