数组中出现一次的两个数 leetcode 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:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.

  1. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
解题思路:有一个数组,其中只有两个数出现一次,其他数均出现两次,求出这两个数。参考signal number的第二种解法:http://blog.csdn.net/sinat_24520925/article/details/45576735
我们将这个数组分成两个数组,每个数组中都只有一个元素出现一次。也就是先异或所有元素,得到resultExclusive,找到resultExclusive中二进制表示的由右向左的第一位1,则表明数组中有一个一次出现的数该位的值不同,一个为0、另一个为0.下面就好做了,将数组中该位均为0的异或,均为1的异或就可求得只出现一次的那两个数。
代码如下:
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> res;
        if(nums.size()==0) return res;
        res.push_back(0);
        res.push_back(0);
        int resultExclusive=0;
        for(int i=0;i<nums.size();i++)
        resultExclusive^=nums[i];
        int indexof1=0;
        while(((resultExclusive&1)==0)&&(indexof1<8*sizeof(int)))
        {
            resultExclusive=resultExclusive>>1;
            ++indexof1;
        }
        for(int i=0;i<nums.size();i++)
        {
            if((nums[i]>>indexof1)&1==1)
            res[0]^=nums[i];
            else
            res[1]^=nums[i];
        }
        return res;
    }
};
值得注意的是::
(resultExclusive&1)==0)
(resultExclusive&1)一定要加(),否则因为==的优先级高于&,会导致while循环无法进入!!!!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值