找到数组中最小的缺失数字

时间:2012-06-22 12:49:02

标签: algorithm

  

可能重复:
  Find the Smallest Integer Not in a List

我在接受采访时被问到这个问题

给定未排序的数组,找到丢失的最小数字。假设所有数字都是正面的。

input = {4,2,1,3,678,3432}

输出= 5

排序是我的第一个方法。我的第二种方法是使用布尔标志数组。第二种方法占用大量空间。

还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:9)

假设给定数组的长度为N。 你可以使用boolean-flag方法,但是你不需要考虑大于N的数字,因为它们显然太大而不能影响答案。您还可以考虑使用bitmap来节省一些空间。

答案 1 :(得分:0)

unkulunkulu的另一种解决方案如下:

k := 1
Make an array of 2^k booleans, all initially set to false
For every value, V, in the array:
  if V < 2^k then:
    set the V'th boolean to true
Scan through the booleans, if there are any falses then the lowest one indicates the lowest missing value.
If there were no falses then increment k and go to step 2.

这将在O(n log s)时间和O(s)空间中运行,其中n是输入数组的大小,s是不存在的最小值。通过不在连续迭代中重新检查最低值可以提高效率,但这不会改变约束。