• 35. 搜索插入位置 今天就是二分法专场


    思路:

      1. 题目前半句 ’给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引‘  就是最普通的二分法

      2. 主要是后半句 ’如果目标值不存在于数组中,返回它将会被按顺序插入的位置‘,不存在目标值的时候,返回值存在两种情况

        返回值是4时,目标值可能是 3 或者 5

        1) 目标值是3的时候: 会替代4的 index,此时直接返回4的Index

        2)    目标值是5的时候: 会插入在4的后面,返回 index + 1

    代码:

      

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            l = 0
            r = len(nums)-1
            mid = -1
            while l <=r:
                mid = l+(r-l)//2
                if nums[mid] <target:
                    l = mid +1
                elif nums[mid]>target:
                    r = mid -1
                else:
                    return mid 
            if nums[mid]<target:
                return mid +1
            else:
                return mid 
  • 相关阅读:
    Python基础检测:20171105
    Python中斐波那契数列的四种写法
    Python中斐波那契数列的四种写法
    学习Python3:20171031
    学习Python3:20171031
    9.3 Trains and Evaluates the MNIST network using a feed dictionary
    9.3 Trains and Evaluates the MNIST network using a feed dictionary
    学习Python3:201701030
    学习Python3:201701030
    周末微光
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12888199.html
Copyright © 2020-2023  润新知