-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSingleNumberIII.java
More file actions
38 lines (34 loc) · 963 Bytes
/
Copy pathSingleNumberIII.java
File metadata and controls
38 lines (34 loc) · 963 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package bitmanipulation;
import java.util.Arrays;
// Source : https://leetcode.com/problems/single-number-iii/
// Id : 260
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-08-02
// Topic : Bit Manipulation
// Level : Medium
// Other :
// Tips :
// Links :
// Result : 100% 16.67%
public class SingleNumberIII {
public int[] singleNumber(int[] nums) {
int ret = 0;
for (int num : nums) {
ret ^= num;
}
// 找到异或结果中第一位不是 0 的,用它来对所有数字进行分组
// 这样两个结果数字会在不同组
// 同时所有相同数组会在一组
int h = 1;
while ((ret & h) == 0)
h <<= 1;
int[] ans = new int[2];
for (int num : nums) {
if ((h & num) == 0)
ans[0] ^= num;
else
ans[1] ^= num;
}
return ans;
}
}