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.
Example:
Input: [1,2,1,3,2,5]Output: [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?
难度:medium
题目:给定整数数组 nums, 数组里有且仅有两个数出现了一次,其它所有的数出现两次,找出这两个只出现一次的数。
你的算法时间复杂度是线性的 O(n),你可以实现空间复杂度为常数吗 O(1)?
思路:1. 由于相同的两数异或结果为 0. 因此数组内所有出现两次的数的异或结果为 0.2. 如果将所有元素异或,即是两个有且仅出现一次的两个数的结果。3. 找出异或结果中任意一位为 1 的结果,它表示这两个数中不一致的位。用它作为分组标准将数组分为两部分,因此两部分各含有一个有且仅出现一次的数。
Runtime: 1 ms, faster than 100.00% of Java online submissions for Single Number III.
class Solution {
public int[] singleNumber(int[] nums) {
int resultXOR = 0;
for (int i = 0; i < nums.length; i++) {
resultXOR ^= nums[i];
}
int oneBitXOR = 0;
for (int i = 0; i < 32; i++) {
if ((resultXOR & (1 << i)) != 0) {
oneBitXOR = 1 << i;
break;
}
}
int[] result = {0, 0};
for (int i = 0; i < nums.length; i++) {
if (0 == (oneBitXOR & nums[i])) {
result[0] ^= nums[i];
} else {
result[1] ^= nums[i];
}
}
return result;
}
}