260. Single NumberIII

题目:
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?

解答:
只能用厉害来形容了!思路是第一个loop找到两个single number的一个同一位不同的bit;第二个loop是通过这bit把所以数分成两个group,因为其它数都是有两个,所以在这两组中,只是这两个数是单一的。再用以后就可以分别求出这两个数了。

public int[] singleNumber(int[] nums) {
int diff = 0;
for (int num : nums) {
diff ^= num;
}
//我们有了这两个数不同的bit
int[] result = new int[2];
diff &= -diff;
for (int num : nums) {
if ((num & diff) == 0) {
result[0] ^= num;
} else {
result[1] ^= num;
}
}
return result;
}

关键字:java, leetcode, int, num


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部