二分查找 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:

 

posted @ 2021-11-11 10:30  Ross_Berteig  阅读(52)  评论(0)    收藏  举报