您的位置:首页 > 其它

Single Number III

2015-08-23 10:13 309 查看
Description:

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?

Code:

vector<int> singleNumber(vector<int>& nums) {
vector<int>result;
if (nums.size() < 2)
return result;
int xorAll = 0;
for (int i = 0; i < nums.size(); ++i)
xorAll^=nums[i];
unsigned int x = 1;
while ((xorAll & x) == 0)
{
x=x<<1;
}
int result1=0,result2=0;
for (int j = 0; j < nums.size(); ++j)
{
if ((nums[j]&x) == 0)
result1^=nums[j];
else
result2^=nums[j];
}
result.push_back(result1);
result.push_back(result2);
return result;
}


PS:

思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: