'''
给定输入的整数数组 nums ,其中的数值升序排列
找到目标值在整数数组中出现的索引下标范围
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
解法:二分查找
'''
class Solution:
def searchRange(self, nums, target: int):
if len(nums)==0:
return [-1,-1]
if len(nums)==1:
if nums[0]==target:
return [0,0]
else:
return [-1,-1]
start=0
end=len(nums)-1
while(start<end):
# print(start,end)
if end-1==start:
if nums[start]!=target and nums[end]!=target:
return [-1,-1]
if nums[start]==target and nums[end]==target:
return [start,end]
if nums[start]==target and nums[end]!=target:
return [start,start]
if nums[start]!=target and nums[end]==target:
return [end,end]
mid=(start+end)//2
if nums[mid]>target:
end=mid
elif nums[mid]<target:
start=mid
else:
left=mid
right=mid
while(left>=1 and nums[left]==nums[left-1]):
left-=1
while(right<len(nums)-1 and nums[right]==nums[right+1]):
right+=1
return [left,right]
return [-1,-1]
if __name__=="__main__":
print(Solution().searchRange(nums = [1,2,2], target = 1))