1. 程式人生 > >LeetCode260 Single Number III

LeetCode260 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.

Example:

Input: [1,2,1,3,2,5]
Output: [3,5]
Note:

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

這次的問題變成special的數又兩個了,實際上題目並不是找single number了,而是找special two number。所以之前兩個題目的解法是不適用的,起碼不是直接適用的。如果可以把two number的問題變成兩個single number的問題,就可以套用之前第一個問題的解法了,也就是說我們可以通過某種方式把陣列分為兩組,每組只包含那兩個special number中的一個。

問題的關鍵就變成如何分組了。思路也是有點巧妙,考慮到兩個special number是不一樣的,而恰好其餘的數都是出現兩次,所以如果對每個數都做亦或操作,最後的結果就是那兩個special number的亦或,而且至少有一個位是1,那麼就可以根據其中一個為1的位將所有的數分為兩組,再套用第一個題的方法即可。

public int[] singleNumber(int[] nums) {
    int diff = 0;
    for(int num: nums){
        diff^=num;
    }
    diff = Integer.highestOneBit(diff);//作用是取這個數的二進位制形式最左邊的最高一位且高位後面全部補零,最後返回int型的結果。

    int[] result = new int[2];
    Arrays.fill(result,0);
    for(int num: nums){
        if((diff & num) == 0){
            result[0] ^= num;
        }
        else{
            result[1] ^= num;
        }
    }
    return result;
}