defsearchRange(self, nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = left + (right-left) // 2 if nums[mid] >= target: # 注意此处的条件 right = mid - 1 else: left = mid + 1 if left >= len(nums) or nums[left] != target: # 注意此处的条件 return [-1, -1] l = left
right = len(nums) - 1 while left <= right: mid = left + (right-left) // 2 if nums[mid] <= target: # 注意此处的条件,如果只是单独返回最后一个相等的元素,还是需要判断一下 right >= 0 and nums[right] == target left = mid + 1 else: right = mid - 1 return [l, right]
返回第一个大于等于 target 的元素,或返回最后一个小于等于 target 的元素
第一个大于等于 target:
1 2 3 4 5 6 7 8 9
defbinarySearch(nums, target): left, right = 0, len(nums)-1 while left <= right: mid = left + (right-left) // 2 if nums[mid] >= target: # 若找第一个大于 target 的,只需要改成 > right = mid - 1 else: left = mid + 1 return left if left < len(nums) else-1
最后一个小于等于 target:
1 2 3 4 5 6 7 8 9
defbinarySearch(nums, target): left, right = 0, len(nums)-1 while left <= right: mid = left + (right-left) // 2 if nums[mid] <= target: # 若找第一个小于 target 的,只需要改成 < left = mid + 1 else: right = mid - 1 return right if right >= 0else-1
defsearch(self, nums, target): left = 0 right = len(nums)-1 while left <= right: mid= left + (right-left) // 2 if nums[mid] == target: return mid if nums[mid] >= nums[left]: if target >= nums[left] and target < nums[mid]: right = mid - 1 else: left = mid + 1 elif nums[mid] <= nums[right]: if target <= nums[right] and target > nums[mid]: left = mid + 1 else: right = mid - 1 return-1
defsearchRange(self, nums, target): left = 0 right = len(nums)-1 index = -1 while left <= right: mid = left + (right-left) // 2 if nums[mid] == target: index = mid break elif target > nums[mid]: left = mid + 1 else: right = mid - 1
if index != -1: i = index - 1 j = index + 1 while i>=0and nums[i] == target: i -= 1 while j <= len(nums)-1and nums[j] == target: j += 1 return [i+1, j-1] else: return [-1, -1]
deffindMin(self, nums): left = 0 right = len(nums)-1 while left < right: mid = left + (right-left) // 2 if nums[mid] <= nums[right]: right = mid else: left = mid + 1 return nums[left]
deffindMin(self, nums): left = 0 right = len(nums)-1 while left < right: mid = left + (right-left) // 2 if nums[mid] == nums[right]: right -= 1 elif nums[mid] < nums[right]: right = mid else: left = mid + 1 return nums[left]
deffindPeakElement(self, nums): if len(nums) <= 1: return0 left = 0 right = len(nums) - 1 while left < right: mid = left + (right-left)//2 if nums[mid] < nums[mid+1]: left = mid + 1 else: right = mid return left
defarrange_coins(n): if n < 0: return-1 low = 0 high = n while(low <= high): mid = low + (high-low)//2 sum = mid * (1+mid) // 2 if sum <= n and sum > n-mid: return mid elif sum > n: high = mid - 1 else: low = mid + 1