LeetCode 35 Search Insert Position (Introduce python bisect) (Python)

Posted by 小明MaxMing on June 10, 2020

题目

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

解题思路

二分搜索

代码

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        # return bisect.bisect_left(nums, target)
        
        l, r = 0, len(nums) - 1
        while l <= r:
            m = (l + r) // 2
            if nums[m] == target:
                return m
            if nums[m] < target:
                l = m + 1
            else:
                r = m - 1
        return l

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅