其他分享
首页 > 其他分享> > 1、代码复用--二分法

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

标签:last,nums,--,mid,beg,复用,二分法,int,return
来源: https://blog.csdn.net/weixin_52663081/article/details/118810663