Leetcode 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.

Example:

Input: [1,2,1,3,2,5]
Output: [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做异或相当于取反
2、相同的数做异或得到0

1o 首先我们要将只出现一次的数从数组中分离出来,那么和single number那道题目一样,将数组中所有数做异或,出现两次的都异或为0不对数值再做影响,所以最后得到的是a XOR b。

2o 那么如何从a XOR b中将a和b分离出来呢?
只这一个数显然不行,所以我们又回到数组,联想single number只一个数出现一次,那么我们这道题是不是可以将原数组分成两部分,一部分包含a,另一部分包含b,然后用single number的方法就可以找到a和b了呢

3o 如何分类原数组将其分成两部分?
既然要找把a和b分在两队,那当然是找a和b的不同了。观察aXORb,该位为0那么说明a和b的该位相同,同为0或同为1;该位为1说明a和b该位上恰一个为0一个为1(究竟是a的这一位为0还是b的这一位为0不重要,因为题目不要求输出顺序) ,以此分类。

综上所述,选择一位aXORb中为1的一位,将原数组中该位为0的分为一组,做异或,结果为a,将原数组中该位为1的分为一组,做异或,结果为b

代码

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int x=0;
        for(auto i:nums){
            x=x^i;
        }
        int index=0;
        int n=sizeof(int)*8;
        for(;index<n;++index){
            if(((x>>index)&1)==1){
                break;
            }
        }
        int a=0;
        int b=0;
        for(auto i: nums){
            if(((i>>index)&1)==0){
                a=a^i;
            }
            else{
                b=b^i;
            }
        }
        
        vector<int> r;
        r.push_back(a);
        r.push_back(b);
        return r;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值