LeetCode 704. 二分查找

704. 二分查找

LeetCode 704. 二分查找

思路:递归经典题,二分查找

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        
        def recur(high,low,target):
            if low > high:
                return -1
            else:
                mid = (high+low) //2
                if nums[mid] == target:
                    return mid
                elif nums[mid]>target:
                    return recur(mid-1,low,target)
                else:
                    return recur(high,mid+1,target)
        return recur(len(nums)-1,0,target)

思路2:
LeetCode 704. 二分查找

class Solution:
    def search(self, nums: List[int], target: int) -> int:

        #python独有写法
        try:
            return nums.index(target)
        except ValueError:
            return -1

思路3:既然能用递归,就可以用迭代

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        #迭代
        def binary_search(high,low):
            while low<=high:
                mid = low + (high-low)//2
                if nums[mid] == target:
                    return mid
                elif nums[mid]<target:
                    low=mid+1
                else:
                    high=mid-1
            return -1
        return binary_search(len(nums)-1,0)
上一篇:[LeetCode] 704. Binary Search


下一篇:LeetCode 704. 二分查找(Binary Search)