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. Use XOR to store the difference among these numbers, if XOR all elements, the result is the difference between two number like result = 3^5
then 3^result = 5 , 5^ result = 3
2. Find one digit 1 in the result, which can be used to distinguish 3 and 5. depends on this, XOR elements will be equal to 3^result = 5 , 5^ result = 3
O(n) use constant space
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
int result = nums[0];
for(int i=1;i<nums.length;i++){
result = result^nums[i];
}
res[0] = 0;
res[1] = 0;
int n = result & (~(result-1));
for(int i=0;i<nums.length;i++){
if((n & nums[i])!=0){
res[0] = res[0] ^ nums[i];
}else {
res[1] = res[1] ^ nums[i];
}
}
return res;
}

本文介绍了一种线性时间和常数空间复杂度的算法,用于从数组中找出仅出现一次的两个元素。通过使用XOR操作来区分这些元素,并进一步细化XOR结果以隔离目标元素。
2595

被折叠的 条评论
为什么被折叠?



