LeetCode刷题实战260:只出现一次的数字 III
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.
Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
示例
示例 1:
输入:nums = [1,2,1,3,2,5]
输出:[3,5]
解释:[5, 3] 也是有效的答案。
示例 2:
输入:nums = [-1,0]
输出:[-1,0]
示例 3:
输入:nums = [0,1]
输出:[1,0]
解题
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> res(2, 0); // 分为两组
int sum = 0; // sum是nums所有元素异或的结果
for(int i = 0; i < nums.size(); ++i) {
sum ^= nums[i];
}
int firstOne = sum & (-sum); // 得到最低位的1,sum & (-sum)这是一个常见的技巧
for(int i = 0; i < nums.size(); ++i) {
if(firstOne & nums[i]) { // 如果和firstOne相与为1,分到第一组(并且第一组所有元素进行异或操作)
res[0] ^= nums[i];
} else { // 否则到第二组(并且第二组所有元素进行异或操作)
res[1] ^= nums[i];
}
}
return res;
}
};