# 260. Single Number III

117人阅读 评论(0)

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.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

1. The order of the result is not important. So in the above example, [5, 3] is also correct.
2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

1.我的答案

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
map<int,int> mp;
vector<int> res;
int len = nums.size();
for(int i = 0; i < len; i++){
if(mp.find(nums[i]) == mp.end()){
mp[nums[i]] = 1;
}
else
mp[nums[i]]++;
}
for(auto iter = mp.begin(); iter != mp.end(); iter++){
if(iter->second == 1)
res.push_back(iter->first);
}
return res;
}
};

2.看了别人答案做的

int bit = a & ~(a-1);

bit即可得到a中右边第一次出现1的数。

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int temp = 0;
for(int i = 0; i < nums.size(); i++){
temp ^= nums[i];
}
int xors = temp & ~(temp - 1);
int num1 = 0, num2 = 0;
for(int j = 0; j < nums.size(); j++){
if((nums[j] & xors) > 0)
num1 ^= nums[j];
else
num2 ^= nums[j];
}
vector<int> res;
res.push_back(num1);
res.push_back(num2);
return res;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：30878次
• 积分：1922
• 等级：
• 排名：千里之外
• 原创：171篇
• 转载：1篇
• 译文：0篇
• 评论：3条
评论排行
最新评论