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]