LeetCode ❀ 35. Search insertion position/implement dichotomy in python

topic

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position at which it will be inserted sequentially.

Please use an algorithm with a time complexity of O(log n) .

Example 1:

输入: nums = [1,3,5,6], target = 5
输出: 2

Example 2:

输入: nums = [1,3,5,6], target = 2
输出: 1

Example 3:

输入: nums = [1,3,5,6], target = 7
输出: 4

answer:

Due to the requirements, please use an algorithm with a time complexity of O(log n) .

According to the question requirements, we naturally think of the dichotomy

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1
        # 注意这里的 right = len(nums) - 1 
        while left <= right :
            middle = (left + right) // 2

            if nums[middle] == target: return middle
            if nums[middle] > target: right = middle - 1
            if nums[middle] < target: left = middle + 1
            # 这里的3个if可以写成一个if
        return right + 1 
        # 注意这里返回的是 right + 1 因为找不到目标时需要嵌入
        # 并返回嵌入位置,所以嵌入的是二分法结束后right的右边一个位置

Guess you like

Origin blog.csdn.net/qq_42395917/article/details/126559058