LeetCode-35. Search Insert Position

本文介绍了一种针对已排序数组查找目标值或确定插入位置的算法。通过三种方法实现:遍历查找、一行代码解决方案及二分查找法。重点介绍了二分查找法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

solution:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        """
        第一种方法:
        如果nums中的某个元素大于等于target,返回该元素的下标,否则应该插入到最后,也就是返回len(nums)
        for i in nums:
            if i >= target:
                return nums.index(i)
        return len(nums)        
        """
       
        """
        第二种方法:
        用一行代码搞定的操作:
        return len([x for x in nums if x < target])
        另一种高级操作:
        'bisect',--- 查找该数值将会插入的位置(索引)并返回,0~全长  'bisect_left'返回左侧元素,  'bisect_right'返回右侧元素   
        'insort',---插入元素,不会影响原排列  'insort_left',  'insort_right同上
        return bisect.bisect_left(nums, target)
        """
        
        """
        第三种方法:
        根据topic中给出的提示是binary search:
                
        """
        start = 0
        end = len(nums)-1
        while start <= end:
            mid = (start+end)//2#注意是整除
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                    start += 1
            else:
                end -= 1
        return start

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值