Search for a Range
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1].
Example
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
Solution
首先得出第一个索引的值, 然后在通过二分法得出最后一个索引的值,返回数组结果。
首先 是如何求出重复值的第一个索引值,与最后一个索引值,一步是不能求出第一个最后一个重复值,因为我们的最后切割后只留下了一个两个月元素的window, 但是重复值有可能是大于两个元素的,所以必须要写两步二分运算. 如果第一个二分法找不到元素就没有必要继续找了直接返回.
Make the mistake and take 1 hour: 二分法写的时候忘记了除2 ,结果导致益出错误: mid = (start + end)
Last updated
Was this helpful?