您的位置:首页 > 其它

Single Number III

2015-11-03 15:07 387 查看
题目:

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?

分析:

这题没想出来

题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。

解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。

注意n&(~(n-1))表示取的n中的第一个为1的且其他置为0,(我也不知道为什么)

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int len = nums.size();
int AxorB = 0;
for(int i=0; i<len; i++){
AxorB ^= nums[i];
}
int mask = AxorB & (~(AxorB-1));
int A = 0;
int B = 0;
for(int i=0; i<len; i++){
if((mask&nums[i])==0){
A ^= nums[i];
}else{
B ^= nums[i];
}
}
return vector<int>({A, B});
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: