[leetcode]260. Single Number III
Analysis
心态奶茶妹妹~—— [马云爸爸恐成最大赢家 哈哈哈]
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.
因为题目对时间复杂度和空间复杂度有要求,所以暴力是不可能的,看了一下大神们的嘴阀,用到了位运算,对位运算不是很清楚,所以先查了一下,总结在:https://blog.csdn.net/weixin_32135877/article/details/82346446
参考的博客是:https://blog.csdn.net/Cloudox_/article/details/53995027
Implement
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int diff = 0;
for(auto num:nums)
diff ^= num;
diff &= -diff;
vector<int> res = {0, 0};
for(auto num:nums){
if((num&diff) == 0)
res[0] ^= num;
else
res[1] ^= num;
}
return res;
}
};