LeetCode | 704.二分查找

时间:2024-10-14 07:49:12

在这里插入图片描述

  • 标准的二分查找,直接上模板!
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        l = 0
        r = len(nums) - 1
        while l <= r:
            mid = (l + r + 1) / 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                l = mid + 1
            else:
                r = mid - 1
        return -1

在这里插入图片描述