34. Find First and Last Position of Element in Sorted Array
defsearchRange(self,nums: List[int],target:int) -> List[int]: first = self.findFirst(nums, target) last = self.findLast(nums, target)print(first, last)if first ==len(nums)or nums[first]!= target or nums[last]!= target:return [-1,-1]return [first, last]deffindFirst(self,nums,target): l, r =0,len(nums)while l < r: mid = (l+r)//2if nums[mid]>= target: r = midelse: l = mid +1return ldeffindLast(self,nums,target): l, r =0,len(nums)while l < r: mid = (l+r)//2if nums[mid]> target: r = midelse: l = mid +1return l -1
162. Find Peak Element
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
deffindPeakElement(self,nums: List[int]) ->int: l, r =0,len(nums)-1while l < r: mid = (l+r)//2if nums[mid]> nums[mid+1]: r = midelse: l = mid+1return l