题目地址:
https://www.lintcode.com/problem/single-number-iii/description
给定一个数组,其中有且仅有两个数各自出现了 次,其余数都出现了 次,要求将那两个出现了 次的数求出来。
基本思路是,假设所要求的两个数分别是 和 ,那么先将所有数异或一遍得 ,其必定非零,否则就会得出 的结论,就矛盾了。接着求出 的lowbit(参考https://blog.csdn.net/qq_46105170/article/details/104082406),就可以将数组中的数 按照 是否为 分为两类,再在这两类中做异或,就可以筛选出所要求的两个数了。代码如下:
public class Solution {
/**
* @param A: An integer array
* @return: An integer array
*/
public List<Integer> singleNumberIII(int[] A) {
// write your code here
int axorb = 0;
for (int i : A) {
axorb ^= i;
}
int lowb = lowbit(axorb);
int a = 0, b = 0;
for (int i : A) {
if ((i & lowb) != 0) {
a ^= i;
} else {
b ^= i;
}
}
return Arrays.asList(a, b);
}
private int lowbit(int x) {
return x & (-x);
}
}
时间复杂度 ,空间 。