Lintcode—落单的数III

落单的数III(Java)

题目

给出2*n + 2个的数字,除其中两个数字之外其他每个数字均出现两次,找到这两个数字。

输入:

[1,2,2,3,4,4,5,3]

输出:

1 5

思路:

首先将所有数字求异或,得到的数是两个落单的数字的异或。由于这两个数字肯定不同,则他们的异或一定有值1的位。找到第一个值为1的位,以这一位为标志,将数组中的数分为两组。一组是该位为1的数字,一组是该位为0的数字。对这两组数分别进行异或,即可找到这两个不同的数字。

Java代码

public class Solution {
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    public List<Integer> singleNumberIII(int[] A) {
            // write your code here
            if( A == null || A.length == 0)
                return null;
            List<Integer> res = new ArrayList<Integer>();
            int n = A.length;
            int tmp = A[0];
            for(int i = 1; i < A.length; i++){
                tmp = tmp ^ A[i];
            }
            int k = findFirstBit(tmp);
             boolean mark1 = true;
             boolean mark2 = true;
             int res1 = 0;
             int res2 = 0;
            for(int i = 0; i < n; i++){
                if((A[i]>>k & 1 )== 0){
                    if(mark1){
                        res1 = A[i];
                        mark1 = false;
                    }
                    else
                        res1 = res1 ^ A[i]; 
                }
                else{
                    if(mark2){
                        res2 = A[i];
                        mark2 = false;
                    }
                    else
                        res2 = res2 ^ A[i]; 
                }
            }
            res.add(res1);
            res.add(res2);
            return res;
        }
     public int findFirstBit(int tmp){
         int res = 0;
         while((tmp & 1) == 0){
             tmp = tmp>>1;
             res ++;
         }
         return res;
     }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值