0
点赞
收藏
分享

微信扫一扫

Leetcode:35.搜索插入位置 Python3

IT程序员 2022-01-20 阅读 54

 

# 二分查找法
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        # 边界条件
        if not nums or len(nums) == 0:
            return 0
        # 左右双指针
        left, right = 0, len(nums)-1
        # 循环体
        while left <= right:
            # 中间值
            mid = left + (right-left)//2
            # 等于目标值
            if nums[mid] == target:
                return mid
            # 大于目标值
            elif nums[mid] > target:
                # 移动右指针
                right = mid - 1
            # 小于目标值
            else:
                # 移动左指针
                left = mid + 1
        # 返回左指针
        return left
举报

相关推荐

0 条评论