跳至主要內容
Binary Search

Summary

1. 二分搜索模板

1.1 基本的二分搜索算法

  1. 手工实现

    class Solution:
        def search(self, nums: List[int], target: int) -> int:
            if not nums:
                return -1
            l, r = 0, len(nums) - 1
            while l <= r:
                mid = l + (r - l) // 2
                if nums[mid] < target:
                    l = mid + 1
                elif nums[mid] > target:
                    r = mid - 1
                else:
                    return mid
    
            return -1
    
  2. 使用 Python bisect

        def search_2(self, nums: List[int], target: int) -> int:
            res = bisect.bisect_left(nums, target)
            if res != len(nums) and nums[res] == target:
                return res
            return -1
    

Someone大约 9 分钟Algorithmalgorithmbinary_search