二分查找 left <= right
二分查找,思路为存储每个iteration的middle,每次循环都剩一个元素
LeetCode 744
class Solution(object): def smallestElementLargerThanTarget(self, array, target): """ input: int[] array, int target return: int """ left = 0 right = len(array) - 1 index = -1 if right < 0: return -1 if not array: return -1 if target < array[left]: return 0 if target >= array[right]: return -1 while left <= right: mid = (left + right) // 2 if array[mid] > target: index = mid right = mid - 1 else: left = mid + 1 return index
LeetCode 34
class Solution(object): def firstOccur(self, array, target): if not array: return -1 index = -1 # updates until the last in the backward direction is found left = 0 right = len(array) - 1 while left <= right: # make sure the search is finished mid = (left + right) // 2 if array[mid] < target: left = mid + 1 else: # don't return values through indexes of boundaries right = mid -1 if array[mid] == target: index = mid return index
lastOccur只需要<=这一行就可以了
if array[mid] <= target:

浙公网安备 33010602011771号