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?
给定一个数组,里面有两个数字出现了一次,其他都出现了两次,找出这两个元素,要求在线性时间内完成。我们用位运算来完成,首先将数组中所有的元素进行异或运算得到一个值helper,然后用helper & (~(helper - 1)) 这样就得到了一个某一位为1其他位全为0的数tell,并且1所在的位上两个单独出现的数肯定不同。我们通过tell将数组中的元素分为两部分,分别与tell进行位与运算,最终得到两个单独的数。代码如下:
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?
给定一个数组,里面有两个数字出现了一次,其他都出现了两次,找出这两个元素,要求在线性时间内完成。我们用位运算来完成,首先将数组中所有的元素进行异或运算得到一个值helper,然后用helper & (~(helper - 1)) 这样就得到了一个某一位为1其他位全为0的数tell,并且1所在的位上两个单独出现的数肯定不同。我们通过tell将数组中的元素分为两部分,分别与tell进行位与运算,最终得到两个单独的数。代码如下:
public class Solution {
public int[] singleNumber(int[] nums) {
if(nums == null || nums.length < 2) return new int[0];
int helper = 0;
for(int i = 0; i < nums.length; i++) {
helper ^= nums[i];
}
int tell = helper & (~(helper - 1));
int single1 = 0;
int single2 = 0;
for(int i = 0; i < nums.length; i++) {
if((nums[i] & tell) == 0) {
single1 ^= nums[i];
} else {
single2 ^= nums[i];
}
}
int[] result = {single1, single2};
return result;
}
}
本文介绍了如何利用位运算解决数组问题,找出仅出现一次的两个元素。通过异或运算得到特定位的1,再根据该位将数组分为两部分,最终得到所需的两个元素。
2万+

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



