34_Search_for_a_Range
question
34. 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 [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
analysis
一开始就想到了二分查找,但是原来做二分查找的时候一般都是找到确定的那个数就完成了,
这里的情况比较特殊,需要找到整个区间,所以需要两遍查找,并且一个是找到小于target
的最大索引,一个是找到大于target的最大索引,代码参考leetcode discuss,这位仁
兄也做了详细的分析解释。
code
1 | class Solution { |