Description
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?
思路
要求时间复杂度O(n),空间复杂度为常量。
基础:
X ^ 0 = X
X ^ X = 0
所以把nums[]中所有数依次进行^运算就能求出结果两个数的异或diff。并且nums[]中两个数不相同,所以俩必有某一位不相同,所以diff中必有某一位是1。
比如diff中最后一位是1,即可把nums[]中的数分为两组,一组是同样最后一位是1的,另一组是最后一位不是1(是0)的。而且result中的两个数一定分在不同组。最后组间进行异或运算即可。
public int[] singleNumber(int[] nums) {
int[] result = new int[2];
int diff = 0;
for(int num : nums) {
diff ^= num;//diff为两个数的异或(^),
}
diff &= -diff;//nums中两个数不相同,它俩必有某一位不相同,所以diff中必有某一位是1。diff & -diff 得到结果是diff中最后一个1的位置。
for(int i=0; i<nums.length; i++) {
if((nums[i] & diff) == 0) {
result[0] ^= nums[i];
}else {
result[1] ^= nums[i];
}
}
return result;
}