您的位置:首页 > 其它

Single Number III & 数组中只出现一次的数字

2015-12-05 16:20 375 查看
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?

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Bit Manipulation

Show Similar Problems

进行两遍异或。

第一遍异或所有元素,得到我们要找的两个元素的异或值。因为我们要找的两个数是不一样的,所以他们异或的结果中肯定有位被置为1.找到其中任意一个被置为1的位,这里我们找最后一个被置为1的位。

第二遍,根据最后一位是否为1,将所有的数分成两组,那么我们要找的两个数必定属于不同的组。然后对这两组分别异或所有元素,就可以得到要找的数了。

注意位操作。

通过将一个数与它的负绝对值进行按位与,可以得到最低位的1。

class Solution
{
public:
vector<int> singleNumber(vector<int>& nums)
{
// Pass 1 :
// Get the XOR of the two numbers we need to find
int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
// Get its last set bit
diff &= -diff;

// Pass 2 :
vector<int> rets = {0, 0}; // this vector stores the two numbers we will return
for (int num : nums)
{
if ((num & diff) == 0) // the bit is not set
{
rets[0] ^= num;
}
else // the bit is set
{
rets[1] ^= num;
}
}
return rets;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: