轉載請注明出處:http://www.cnblogs.com/liangyongrui/p/6354552.html?
?
異或的妙用。
leetcode124。?
一開始讀題不仔細,以為有很多的孤立數字。
沒想到就兩個- -
?
leetcode15、然后參考了別人的思路。
?
具體見代碼:
public int[] singleNumber(int[] nums) {// Pass 1 : // 把所有的數字相異或,這相當于對兩個只出現了一次的數字做異或int diff = 0;for (int num : nums) {diff ^= num;}// 得到一個為1的位(準確說得到了最后一個)// 由于該位為1,也就是兩個數中,有一個數這個位為1,另一個為0diff &= -diff;// Pass 2 :int[] rets = {0, 0}; // this array stores the two numbers we will returnfor (int num : nums) {//分別相與歸類 if ((num & diff) == 0) { // the bit is not setrets[0] ^= num;}else { // the bit is setrets[1] ^= num;}}return rets;}
?