260-Single Number III

kevin聰發表於2018-04-24

Description

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?

問題描述

給定整數陣列nums, 除了兩個數只出現一次, 其他數都出現了兩次, 找出這兩個只出現了一次的數


問題分析

兩次迴圈處理

  1. 第一次。 異或所有元素, 得到res1 和 res2的異或(由於相等的元素異或為0, 所以消去了)
  2. 第二次。由於res1和res2不同, 那麼我們得到最右邊的不同的那一位,通過這一位將nums分為兩組(使用&為0一組, 使用&不為0一組),分別對兩組數異或, 得到結果(注意, 相等的元素一定落到同一組, 因此消去)

解法

public class Solution {
    public int[] singleNumber(int[] nums) {
        if(nums == null || nums.length <= 1)    return new int[2];

        int diff = nums[0];
        //第一次迴圈, 求出res1和res2的異或
        for(int i = 1; i<nums.length; i++)  diff ^= nums[i];
        //算出最右邊的不同的那一位
        diff &= -diff;

        int res1 = 0, res2 = 0;
        //將元素分為兩組, 分別異或
        for(int num:nums){
            if((num & diff) == 0)   res1 ^= num;
            else                    res2 ^= num;
        }

        return new int[]{res1, res2};
    }
}

相關文章