位运算-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].

思考:

跟出现一次只有一个数那到题稍微难一些,出现一次,直接每一个异或运算即可,但是这里每一个异或运算后,得到的只是两个的异或运算结果,思路就是取两个数字的从低位到高位第一个不同的二进制位,也就是下面的result & (~(result-1));,这样就可以区分了,这样以这个数为底的和每一个数与运算,出现两次的自然会使用异或运算为0,或两个数字的与运算要嘛为0要嘛不为0。

代码:

public class SingleNumber_III {

	public int[] singleNumber(int[] nums) {
        int[] res = new int[2];  
        int result = nums[0];  
        for(int i=1;i<nums.length;i++){  
            result = result^nums[i];  
        }  
        res[0] = 0;  
        res[1] = 0;  
        int n = result & (~(result-1));  
        for(int i=0;i<nums.length;i++){  
            if((n & nums[i])!=0){  
                res[0] = res[0] ^ nums[i];  
            }else {  
                res[1] = res[1] ^ nums[i];  
            }  
        }  
        return res; 
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值