原題的描述如下:
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;
}
}