260. Single Number III
转载
260. Single Number III
题目
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 nunmber iii
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int > vec;
int result = 0;
for (int i = 0; i < nums.size();i++)
{
result ^= nums[i]; //改变了nums[0]的值,后续使用有问题
}
//两个不同的数在不同的位上,若数字不同,则相应的位为1
if (result==0)
{
return vec;
}
//用flag找出num第一个不为0的位
int flag = 1;
while ( (flag&result) == 0) // (flag&result) == 0
{
flag = flag << 1;
}
int data1=0, data2=0; //0 异或任何数是保留原值的作用
for (int j = 0; j < nums.size();j++)
{
if (nums[j]&flag) //某一位,相同的数与操作进同一分支
{
data1 ^= nums[j];
}
else
{
data2 ^= nums[j];
}
}
vec.push_back(data1);
vec.push_back(data2);
return vec;
}
};
题目来源
C/C++基本语法学习
STL
C++ primer
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。