寻找两个只出现一次的数字

题目

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof

解法

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
class Solution {
public int[] singleNumbers(int[] nums) {
if (nums==null|| nums.length==0) {
return new int[0];
}

int k = 0; //异或得到的结果
int len = nums.length;
for(int i=0; i<len; i++) {
k = (k^nums[i]);
}
// 寻找k低位中第一个为1的位置
int mask = 1;
while((k&mask) == 0) {
mask <<= 1;
}

// 分组,再异或
int a = 0, b=0;
for(int i=0; i<len; i++) {
if((nums[i] & mask) == 0) {
a ^= nums[i];
} else {
b ^= nums[i];
}
}
return new int[]{a, b};
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×