LeetCode题解:Single Number III

来源:互联网 发布:windows live软件包 编辑:程序博客网 时间:2024/06/05 17:55

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?

题意:给定数组,除了两个数只出现了一次,其他数都出现了两次,找出出现一次的两个数。

思路:其实和Single Number一样,只是加了个技巧,先用一个数存储所有数异或的结果,那么该数必然是出现次数为1的两个数的异或结果。在该结果的二进制表示中,值为1的位必然是这两个数不同的位,例如3(011)和5(101),有两位不同。这就意味着必然有某一位,一个数在该处的值为1,另一个为0。这样我们就可以把原数组的数分为两组,分别用Single Number的方法找出这两个数了。

代码:

public class Solution {    public int[] singleNumber(int[] nums) {        if(nums == null || nums.length == 0){            return null;        }        int diff = 0;        for(int num : nums){            diff ^= num;        }        diff &= -diff;        int[] result = new int[2];        for(int num : nums){            if((num & diff) == 0){                result[0] ^= num;            }else{                result[1] ^= num;            }        }        return result;    }}
0 0