您的位置:首页 > 其它

[260]Single Number III

2015-10-14 11:15 246 查看
【题目描述】

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:

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?

【思路】

思路和Single Number的类似,依然是用三种方法实现的,个人认为第三种最巧妙,但是在时间紧迫的情况下其实想到前两种更容易。

【代码】

1.

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> ans;
int cnt=0;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-1;i++){
if(nums[i]==nums[i+1]) i++;
else{
ans.push_back(nums[i]);
cnt++;
}
if(cnt==2) return ans;
}
ans.push_back(nums[nums.size()-1]);
return ans;
}
};


2.

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> ans;
map<int,int> m;
for(int i=0;i<nums.size();i++){
if(m.find(nums[i])==m.end()){
m.insert(pair<int,int>(nums[i],nums[i]));
}
else{
m.erase(m.find(nums[i]));
}
}
map<int,int>::iterator it;
it=m.begin();
for(it;it!=m.end();it++){
ans.push_back(it->second);
}
return ans;
}
};


3.

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int axorb=0;
for(int i=0;i<nums.size();i++){
axorb^=nums[i];
}
int lastbit=(axorb & (axorb - 1)) ^ axorb;//discuss里有人用的是axorb<span style="color: rgb(199, 37, 78); font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 15.5844163894653px; background-color: rgb(249, 242, 244);"> &= -axorb,更巧妙</span>
int a,b;
a=b=0;
for(int i=0;i<nums.size();i++){
if(lastbit&nums[i]) a^=nums[i];
else b^=nums[i];
}
return vector<int> {a,b};

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: