原题的描述如下:
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1.咋一看到这个题目一定会似曾相似,大家一定遇到过一个数组中求得其中单独出现一次的一个数。无非就是把数组中的数全部异或处理就得到了该数组中出现了一次的数。
2.该题的解题思路借鉴这一思路,无非是按照一定的规则把包含两个出现一次的数A和B分成两个分别包含A和B的小数组,这样就可以利用1中的思想。
3.该规则应该如何来设计呢?这就需要借助位运算的思想。具体如下:1)把数组全部异或运算,得到的是res=A^B。找到res中的一个位点为1的位,如找到最右边的位1的位:
res=res&-res;然后依据该位来把大数组分成两个小数组,此时A&res和B&res一定不相同,所以可以分成两个不同的数组。这样就可以借助1中的思想了。具体代码如下:
public class Solution {
public int[] singleNumber(int[] nums) {
int length=nums.length;
int [] re=new int[2];
int res=0;
for(int i=0;i<length;i++)
{
res=res^nums[i];
}
res=res&-res;
for(int j=0;j<length;j++)
if((res&nums[j])==0)
re[0]=re[0]^nums[j];
else re[1]=re[1]^nums[j];
return re;
}
}