Skip to content

Commit 82b2ae9

Browse files
committed
upload 1 answer, Aug 17th
1 parent 3b69fc4 commit 82b2ae9

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Medium/SingleNumberIII.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
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.
3+
4+
For example:
5+
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
6+
7+
Note:
8+
The order of the result is not important. So in the above example, [5, 3] is also correct.
9+
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
10+
*/
11+
12+
public class SingleNumberIII {
13+
/*
14+
先将所有的数异或,得到的将是x和y以后之后的值n。 因为这两个数一定是不同的,所以最终异或的值至少有一个位为1
15+
找到这个数n的为1的某一位(为了方便就取最右边为1的一位, n & ~(n-1)),然后根据该位的值是否为1,将数组中的每一个数,分成两个部分
16+
这样每个部分,就可以采用Sing number I中的方法得到只出现一次的数
17+
*/
18+
public int[] singleNumber(int[] nums) {
19+
int[] res = new int[2];
20+
int n = 0;
21+
for (int elem : nums) {
22+
n ^= elem;
23+
}
24+
n = n & (~(n-1));
25+
for (int elem : nums) {
26+
if ((elem & n) != 0) {
27+
res[0] = res[0]^elem;
28+
}
29+
else res[1] = res[1]^elem;
30+
}
31+
return res;
32+
}
33+
}
34+
35+
/*
36+
https://leetcode.com/discuss/52351/accepted-java-space-easy-solution-with-detail-explanations
37+
http://www.cnblogs.com/EdwardLiu/p/4391455.html
38+
https://richdalgo.wordpress.com/2015/02/01/lintcode-single-number-iii/
39+
https://github.com/shawnfan/LintCode/blob/master/Java/Single%20Number%20III.java
40+
http://www.wengweitao.com/lintcode-single-number-i-ii-iii-luo-dan-de-shu.html
41+
*/

0 commit comments

Comments
 (0)