天天看點

LeetCode: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?
Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

題意:給定數組中有且隻有兩個數隻出現1次,其他數全部出現2次,找出這兩個數。

分析:找出出現1次的數,首先想到異或操作,然而存在兩個隻出現1次的數,那就要想辦法把這兩個數分開。因為這兩個數不同(如果相同,那麼都出現兩次),說明兩個數的二進制表示中至少有一位是不相同,如果根據該位将數組分成兩部分,然後分别異或,那麼兩組的異或結果便是這兩個數。那麼如何找到二進制不同的位呢?可以先對整個數組異或,結果必然不是0,隻要找到這個異或結果的某一非0位,即是兩個數不同的位。

代碼如下:

class Solution {
    public int[] singleNumber(int[] nums) {
        int n=;
        for(int i=;i<nums.length;i++){
            n=n^nums[i];
        }
        int m=;
        while((n&m)==) m=m<<;
        n=;
        int n2=;
        for(int i=;i<nums.length;i++){
            if((nums[i]&m)==){
                n=n^nums[i];
            }
            else
                n2=n2^nums[i];
        }
        int[] result=new int[];
        result[]=n;
        result[]=n2;
        return result;
    }
}