LeetCode -- Single Number III

Question:

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?

Analysis:

给出一个整数数组nums,其中只有两个元素只出现一次,其他的元素均出现2次,试找出其中只出现一次的两个整数。

例如:nums = {1, 2, 1, 3, 2, 5}, 则应返回{3, 5}.

注意:

1. 返回结果的顺序是不重要的,因此在给定的例子中,{5, 3}也是正确的;

2. 你的算法应该在线性时间内返回结果。你能仅使用常数的空间复杂度而完成算法嘛?

分析:在前面的Single Number问题中我们知道了使用异或可以将出现偶数次的数据都清除,这样如果将所有数字都进行异或运算得到的结果为只出现一次的两个数的异或。下面我们利用他们的异或结果得到a,b的二进制从低位到高位最开始不一样的位数,然后再进行一次异或运算即可。查阅网上的资料,得知在已知a,b的异或的情况下,使用式子

int xorxor = xor & (~(xor-1))

可以得到第一位不一样的序号。这样我们将数组中的所有元素分为两类,分别进行异或运算,即可以将两个单独出现的数找出来。

Answer:

public class Solution {
    public int[] singleNumber(int[] nums) {
        if(nums == null || nums.length == 0)
            return new int[2];
        int[] result = new int[2];
        int xor = 0;
        for(int x : nums) {
            xor = xor ^ x;
        }
        int firstDif = xor & (~(xor - 1));
        for(int x : nums) {
            if((x & firstDif) != 0)
                result[0] = result[0] ^ x;
            else result[1] = result[1] ^ x;
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/5201547.html