Description
给定sorted list & target num,返第一次&最后一次出现的位置
复习Binary Search模板
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def search(nums,target,first=True):
start = 0
end = len(nums)-1
while start +1 < end:
mid = (start+end)//2
if target > nums[mid]:
start = mid
elif target < nums[mid]:
end = mid
else:
if first is True:
end = mid
else:
start = mid
if first is True:
if nums[start] == target:
res = start
elif nums[end] ==target:
res = end
else:
res = -1
else:
if nums[end] ==target:
res = end
elif nums[start] == target:
res = start
else:
res = -1
return res
if len(nums)==0:
return [-1,-1]
fin_start = search(nums,target,first=True)
fin_end = search(nums,target,first=False)
return [fin_start,fin_end]
网友评论