【发布时间】:2016-04-21 12:10:19
【问题描述】:
我正在尝试回答以下问题:您有一个整数数组,这样每个整数都会出现奇数次,其中 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());
}
}
}
它工作正常,但效率不高。
o/p:
1
5
6
8
但问题指定我们需要在 O(1) 空间和 O(N) 时间复杂度内执行此操作。对于我的解决方案,时间复杂度是 O(N),但空间也是 O(N)。有人可以建议我用 O(1) 空间做这件事的更好方法吗?
谢谢。
【问题讨论】:
-
“除了 3 个”,你的例子有 4 个!?!
-
实际上第一条语句与代码和输出冲突。因此,当其他解决方案显示找到除非配对之外的所有整数的方法时,一些解决方案尝试找到三个非配对整数。请编辑您的问题并严格说明您想要什么!
-
由于您必须再次遍历地图以检索结果,时间复杂度不会超过 O(N) 吗?任何你可以就地排序的方法。时间会增加到 n*log(n) 或它的一些变化,但你的空间复杂度会降低到零!
-
我当然希望问题不在于数字(对于在 N 之前固定的任何基数)——这个例子没有给出任何线索。
-
衡量你可以做什么:discussion of scalability.
标签: algorithm data-structures bit-manipulation time-complexity space-complexity