Finding a gap in an ordered range of adjacent numbers

风流意气都作罢 提交于 2019-12-13 12:41:41

问题


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 from 1 to m where n < m. Give an O(lgN) algorithm to find an integer <= m that is not present in A. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!