每日一道Leetcode - 704. 二分查找 【二分查找|递归】

每日一道Leetcode - 704. 二分查找 【二分查找|递归】_第1张图片

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        """
        n = len(nums)
        l = 0
        r = n - 1
        while l <= r:
            mid = l + (r-l)//2
            if nums[mid] == target:
                return mid
            elif nums[mid]>target:
                r = mid - 1
            elif nums[mid]
        def getTarget(nums,left,right):
            if left == right:
                return left if nums[left]==target else -1
            mid = left + (right-left)//2
            if nums[mid]==target:
                return mid
            elif nums[mid] < target:
                index = getTarget(nums,mid+1,right)
            elif nums[mid] > target:
                index = getTarget(nums,left,mid-1)
            return index
        
        if target<nums[0] or target>nums[-1]:
            return -1
        return getTarget(nums,0,len(nums)-1)
        


你可能感兴趣的:(Leetcode,leetcode)