Leetcode260 Single Number III

来源:互联网 发布:软件设计方案模板 编辑:程序博客网 时间:2024/06/06 03:36

leetcode代码已经放入github:[https://github.com/gaohongbin/leetcode](https://github.com/gaohongbin/leetcode)
题目:
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?

翻译:
给一个数组,在这个数组中,只有两个数只出现了一次,其他所有的数都在数组中出现了两次。找出这两个只出现了一次的数。

小提示:
1.结果中两个数的顺序没有要求。
2.你的算法时间复杂度可以为O(n)吗?你的空间复杂度可以为O(1)吗?

思路:
假设数组中只出现一次的数分别为A,B;
我们都知道 X^X=0; 所以如果将数组中的数字全部进行异或处理,则结果与 A^B相等. 而且因为A!=B,则A^B!=0.
则A,B用二进制表示时1的位置也不尽相同。
N&(-N)的结果为N的最右边的1和后面所有0所组成的整数。
例: N=6 即(0110)
则 6 &(-6) =2;

因为这个1是从A^B中找出来的,则A和B的二进制在该位置上肯定一个为0,一个为1.

依据这样就可以把整个数组分为两大类,(1)该二进制位为1的数
(2)该二进制位为0的数

现在我们只需要在这被划分的两个数组中,分别找出只出现一次的那个数即可。

代码:

public int[] singleNumber(int[] nums) {            int length=nums.length;            int AxorB=0;            for(int i=0;i<length;i++){                AxorB=AxorB^nums[i];            }            int mask=AxorB & (-AxorB);            int A=0,B=0;            for(int i=0;i<length;i++){                if((mask & nums[i])==0)                    A^=nums[i];                else                    B^=nums[i];            }            int[] singleNumber=new int[]{A,B};            return singleNumber;        }
0 0
原创粉丝点击