題目描述:
Given an array of integers nums
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]
.
分析:
Search for a range:
pre: a inc list of int and the target val
post: the range for the val in the list of [-1,-1]
與普通的二分法要進行改進:
當mid的值與val值相同時,要從head->mid和從mid->tail中選出新的前後值
這裏採取先選擇head值,重複操作,直到head和tail對應的數據等於目標值val,退出循環。
class Solution:
def searchRange(self, nums, val):
head = 0
tail = len(nums)-1
mid = (head+tail)//2
while head < tail:
flag = 0
if ( nums[mid] < val ):
head = mid+1
mid = (head+tail)//2
elif nums[mid] > val :
tail = mid-1
mid = (head+tail)//2
elif nums[head] < val :
mid = (head+mid)//2
elif nums[tail] > val :
mid = (tail+mid)//2+1
else :
break
ans = []
if ( head >= len(nums) or nums[head] != val ):
ans.append(-1)
ans.append(-1)
else :
ans.append( head)
ans.append( tail )
return ans