天天看點

[LeetCode] Search for a Range 搜尋一個範圍

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return <code>[-1, -1]</code>.

For example,

Given <code>[5, 7, 7, 8, 8, 10]</code> and target value 8,

return <code>[3, 4]</code>.

這道題讓我們在一個有序整數數組中尋找相同目标值的起始和結束位置,而且限定了時間複雜度為O(logn),這是典型的二分查找法的時間複雜度,是以這道題我們也需要用此方法,我們的思路是首先對原數組使用二分查找法,找出其中一個目标值的位置,然後向兩邊搜尋找出起始和結束的位置,代碼如下:

解法一:

可能有些人會覺得上面的算法不是嚴格意義上的O(logn)的算法,因為在最壞的情況下會變成O(n),比如當數組裡的數全是目标值的話,從中間向兩邊找邊界就會一直周遊完整個數組,那麼我們下面來看一種真正意義上的O(logn)的算法,使用兩次二分查找法,第一次找到左邊界,第二次調用找到右邊界即可,具體代碼如下:

解法二:

繼續閱讀