我试图回答以下问题:给定一个整数数组,其中每个整数出现次数都是奇数,除了其中的3个数字。请找出这三个数字。
到目前为止,我想到了暴力方法:
public static void main(String[] args) {
// TODO Auto-generated method stub
int number[] = { 1, 6, 4, 1, 4, 5, 8, 8, 4, 6, 8, 8, 9, 7, 9, 5, 9 };
FindEvenOccurance findEven = new FindEvenOccurance();
findEven.getEvenDuplicates(number);
}
// Brute force
private void getEvenDuplicates(int[] number) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : number) {
if (map.containsKey(i)) {
// a XOR a XOR a ---- - -- - - odd times = a
// a XOR a ---- -- -- --- - even times = 0
int value = map.get(i) ^ i;
map.put(i,value);
} else {
map.put(i, i);
}
}
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
System.out.println(entry.getKey());
}
}
}
它可以工作,但不够高效。
输出:
1
5
6
8
但是问题指定我们需要在O(N)时间复杂度和O(1)空间复杂度内完成。 我的解决方案的时间复杂度是O(N),但空间复杂度也是O(N)。 有人能建议我用O(1)空间复杂度更好的方法吗?谢谢。