首页 > 其他 > 详细

LeetCode 260. Single Number III

时间:2017-01-28 22:06:52      阅读:280      评论:0      收藏:0      [点我收藏+]

转载请注明出处:http://www.cnblogs.com/liangyongrui/p/6354552.html 

 

异或的妙用。

 

一开始读题不仔细,以为有很多的孤立数字。

没想到就两个- -

 

然后参考了别人的思路。

 

具体见代码:

    public int[] singleNumber(int[] nums) {
        // Pass 1 : 
        // 把所有的数字相异或,这相当于对两个只出现了一次的数字做异或
        int diff = 0;
        for (int num : nums) {
            diff ^= num;
        }
        // 得到一个为1的位(准确说得到了最后一个)
        // 由于该位为1,也就是两个数中,有一个数这个位为1,另一个为0
        diff &= -diff;
        
        // Pass 2 :
        int[] rets = {0, 0}; // this array stores the two numbers we will return
        for (int num : nums) {
            //分别相与归类 
            if ((num & diff) == 0) { // the bit is not set
                rets[0] ^= num;
            }
            else { // the bit is set
                rets[1] ^= num;
            }
        }
        return rets;
    }

 

LeetCode 260. Single Number III

原文:http://www.cnblogs.com/liangyongrui/p/6354552.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!