Search for a Range
Given an array of integersnumssorted in ascending order, find the starting and ending position of a giventargetvalue.
Your algorithm's runtime complexity must be in the order ofO(logn).
If the target is not found in the array, return[-1, -1].
Example 1:
Input:
nums = [
5,7,7,8,8,10]
, target = 8
Output:
[3,4]Example 2:
Input:
nums = [
5,7,7,8,8,10]
, target = 6
Output:
[-1,-1]Analysis
寻找有重复的有序数列中的特定元素的下标范围,需要寻找左边界和右边界。这样单一的binary search会比较难实现,因此用两个binary search,一个找左边界,一个找右边界。
比较偏好Template #3,left + 1 < right作为循环条件,这样结尾的时候有两个备选,满足left + 1 >= right。
寻找左边界
寻找右边界
区别就在于target == nums[mid]时,是往右搜索(右边界)还是往左搜索(左边界)。
Solution
Using Template #3 - Two Binary Searches (6 ms, 33.53%)
Combined two binary searches In Helper function - (6ms 33.53%)
Last updated
Was this helpful?