260. 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].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

一刷
題解:

  1. 通過遍歷整個數(shù)組并求整個數(shù)組所有數(shù)字之間的 XOR,根據(jù) XOR 的特性可以得到最終的結(jié)果為 AXORB = A XOR B;
  2. 通過某種特定的方式,我們可以通過 AXORB 得到在數(shù)字 A 和數(shù)字 B 的二進(jìn)制下某一位不相同的位;因為A 和 B 是不相同的,所以他們的二進(jìn)制數(shù)字有且至少有一位是不相同的。我們將這一位設(shè)置為 1,并將所有的其他位設(shè)置為 0,我們假設(shè)我們得到的這個數(shù)字為 bitFlag;
  3. 那么現(xiàn)在,我們很容易知道,數(shù)字 A 和 數(shù)字 B 中必然有一個數(shù)字與上 bitFlag 為 0;因為bitFlag 標(biāo)志了數(shù)字 A 和數(shù)字 B 中的某一位不同,那么在數(shù)字 A 和 B 中的這一位必然是一個為 0,另一個為 1;而我們在 bitFlag 中將其他位都設(shè)置為 0,那么該位為 0 的數(shù)字與上 bitFlag 就等于 0,而該位為 1 的數(shù)字與上 bitFlag 就等于 bitFlag
  4. 現(xiàn)在問題就簡單了,我們只需要在循環(huán)一次數(shù)組,將與上 bitFlag 為 0 的數(shù)字進(jìn)行 XOR 運算,與上 bitFlag 不為 0 的數(shù)組進(jìn)行獨立的 XOR 運算。那么最后我們得到的這兩個數(shù)字就是 A 和 B。
public class Solution {
    public int[] singleNumber(int[] nums) {
        //pass 1
        int diff = 0;
        for(int num : nums){
            diff ^= num;
        }
        
        //get its last set bit
        diff = diff & (-diff);
        
        //pass 2
        int[] res = new int[2];
        for(int num : nums){
            if((num & diff) == 0){
                res[0] ^= num;
            }else{
                res[1] ^= num;
            }
        }
        return res;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容