码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 260. Single Number III

时间:2017-01-28 22:07:19      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:enum   div   link   his   entry   归类   tco   .com   return   

转载请注明出处: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

标签:enum   div   link   his   entry   归类   tco   .com   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!