Description:
Given an array of integers sorted in ascending order, 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]
.
算法分析:
1. 二分法
2. 二分法的框架, 需要考虑的位置有 3 个, 在代码中我标了出来, 分别为 q1, q2, q3
3. q1 是取 <= 还是取 <. 我的经验是, 若是题目要求找到 target, 那么就用 <=, 否则用 <. 我记得在二分搜索题时, 都是用 < 的
4. q2 比较容易, 考虑当 low == high 时, 我们希望游标往哪里走
5. q3, 返回 low/high. q3 的选取与 q2 有关. 还是需要考虑当 low == high 时, 游标会往哪走
代码:
class Solution:
def searchRange(self, A, target):
if len(A) == 0:
return [-1, -1]
start, end = 0, len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if A[mid] < target:
start = mid
else:
end = mid
if A[start] == target:
leftBound = start
elif A[end] == target:
leftBound = end
else:
return [-1, -1]
start, end = leftBound, len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if A[mid] <= target:
start = mid
else:
end = mid
if A[end] == target:
rightBound = end
else:
rightBound = start
return [leftBound, rightBound]