简体   繁体   English

如果数组中有数百万个数字,如何找到缺失的数字?

[英]How to find a missing number if a range of millions of numbers in an array?

I want to get the first missing number in a range of millions of numbers.我想获得数百万个数字中第一个缺失的数字。 For example, I have an array with n number of elements.例如,我有一个包含n个元素的数组。 And it starts from 0. And in between for example, after 4380, 4381 is missing and is continued with 4382. So, how can I find that 4381?它从 0 开始。在这之间,例如,在 4380 之后,4381 丢失并与 4382 接续。那么,我如何才能找到 4381?

I have seen this questions on many sites including SO, Quora and many more.我在很多网站上看到过这个问题,包括 SO、Quora 等等。 But, all I could find was with a small range of numbers.但是,我所能找到的只是一小部分数字。 For which, a for loop is the best choice.为此,for 循环是最佳选择。 But, when we have millions of numbers in an array, then this wont be both time and memory efficient.但是,当我们在一个数组中有数百万个数字时,这将不会在时间和 memory 上都高效。 What can be used in this case to get it done having both the time and memory in consideration?在这种情况下可以使用什么来完成同时考虑时间和 memory 的工作?

NOTE: The elements are ordered in ascending order注意:元素按升序排列

So when you have a sorted array of n elements starting at 0 then there is a clear correlation between an element's index and value (assuming there can be no duplicates):因此,当您有一个从0开始的n元素的排序数组时,元素的索引和值之间存在明显的相关性(假设没有重复项):

index   value
0       0
1       1
2       2
...
100     100

So you can use a binary-search approach and check eg the element at length / 2 .因此,您可以使用二进制搜索方法并检查length / 2的元素。 If the value is greater than its index, there has to be a missing number somewhere below.如果该值大于其索引,则必须在下方某处缺少数字。

index   value
0       0
1       1
2       2
...
100     100
101     102
102     103
...
204     205

In this example, if you would check index 102 you would see a value of 103 , so between index 0 and 102 there has to be a missing number.在此示例中,如果您检查索引102 ,您会看到值103 ,因此在索引0102之间必须有一个缺失的数字。 Now, repeat the algorithm for the sub-array 0..101 until you have found the missing element.现在,对子数组0..101重复该算法,直到找到丢失的元素。 Otherwise, proceed with the other half.否则,继续另一半。

If elements do not start at 0 it would be easy to add a constant value everywhere.如果元素不从0开始,则很容易在任何地方添加一个常量值。

If there can be arrays without a missing number, you can also start by comparing the last element and abort immediately if the value is equal to its index.如果可以有 arrays没有缺失数字,您也可以从比较最后一个元素开始,如果值等于它的索引则立即中止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM