leetcode 每日一题 34. 在排序数组中查找元素的第一个和最后一个位置
二分法:
思路:
先用二分法找到左边界,再用二分法找到右边界。
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if not nums: return [-1,-1] def searchEdge(nums,target,isleft): l,r = 0,len(nums) while l<r: mid = (l+r)//2 if nums[mid]>target or (isleft and nums[mid]==target): r = mid else: l = mid + 1 return l leftIndex = searchEdge(nums,target,True) if leftIndex == len(nums) or nums[leftIndex]!=target: return [-1,-1] return [leftIndex,searchEdge(nums,target,False)-1]