leetcode260-single number iii

shuaishuai3409發表於2016-04-29

題目:
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:
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?

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

        // get the xor result of the two single numbers
        int xor = 0;
        for (int num : nums)
            xor ^= num;

        // divide the numbers into two groups, get the mask to calculate which group will each number be put in
        int mask = 0;
        if (xor==0) {
            return new int[]{};
        } else if (xor>0) {
            for (int i=1; i<32; i++) {
                int remainder = xor%2;
                if (remainder>0) {
                    mask = 1 << (i-1);
                    break;
                }

                xor = xor/2;
            }
        } else {
            mask = Integer.MIN_VALUE;
        }

        // num1 is the xor result for group 1, and num2 is for group2
        int num1 = 0;
        int num2 = 0;
        for (int num : nums) {
            int group = num & mask;
            if (group==0)
                num1 ^= num;
            else
                num2 ^= num;
        }

        return new int[]{num1, num2};
    }
}

相關文章