问题
This is a homework exercise from Steven Skiena's "The algorithm design manual" 2nd edition, p 143.
Suppose that you are given a sorted sequence of distinct integers
{A1,A2,...An}
, drawn from1
tom
wheren < m
. Give anO(lgN)
algorithm to find an integer<= m
that is not present inA
. For full credit, find the smallest such integer.
A sorted sequence, and O(lgN)
both suggest a binary search algorithm. The only way I could think of is to run through numbers from 1
through m
, and for each number do a binary search to see if it exists in sequence A
. But that means O(mlgN)
, not really O(lgN)
.
回答1:
There is an integer less than A[k]
missing if and only if
A[k] > k
(using 1-based indexing).
So to find the smallest missing number, binary search. Start with the middle index m
. If A[m] > m
, then there is a number smaller than A[m]
missing, search in the left half. Otherwise, if A[m] == m
, there is no smaller number than m
missing, and you search the right half.
来源:https://stackoverflow.com/questions/13793764/finding-a-gap-in-an-ordered-range-of-adjacent-numbers