1、代码复用--二分法

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        #开始是第一个位置,last指向最后
        #比较中间的,大于中间值则将beg换成mid+1,否则将last换成mid-1
        beg =0
        last = len(nums) - 1
        mid  = (beg + last)//2
        if target not in nums:
            return -1
            
        if len(nums) == 1:
            if target == nums[0]:
                return 0
            else:
                return -1    
           
        while beg <= last:
            if target == nums[mid]:
                return mid
            elif target > nums[mid]:
                beg = mid + 1
                mid  = (beg + last)//2
            else:
                last = mid - 1
                mid  = (beg + last)//2

上一篇:复原IP地址


下一篇:最长回文子串