260. Single Number III
Given an array of numbers 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.
Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
Note:
- The order of the result is not important. So in the above example, [5, 3] is also correct.
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Approach
- 题目大意就是有两个数只出现过一次,而其他数出现两次,返回这两个数。这道题挺需要技巧的,我还是将所有都异或一次,最后结果肯定是这两个数异或后的结果,然后我们要区分它们,我们就要随便找到这两个数中某个位的不同,然后再对数组中的数进行区分,一个是这个位为1和一个是这个位为0,然后再异或最后就会得到两个数。
Code
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int diff = 0;
for (const int&n : nums) {
diff ^= n;
}
diff &= -diff;
vector<int>res(2, 0);
for (const int&n : nums) {
if (n&diff)res[0] ^= n;
else res[1] ^= n;
}
return res;
}
};