【LeetCode】Search Insert Position

本文介绍了一种简单算法,用于在已排序的数组中查找指定元素的位置或确定新元素的正确插入位置。通过遍历数组,算法能在O(n)时间内解决此问题,并提供了C++与Python两种实现方式。

摘要生成于 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.

Here are few examples. 
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0


     思路:

     给定一个有序数组,和一个目标元素,如果目标元素存在,则给出其在数组中对应的下标。不存在则返回一个整数,表明目标元素应该插入到数组中的位置。

     很简单的一道题,只要遍历数组,有以下情况:

     1. 如果找到该元素,直接返回其下标

     2. 遇到第一个比它大数,返回这个数的下标。

     3. 找不到比它大的数,那么应该插入到最后,返回 n。

     情况 1 2 可以写在一起。


     代码:

     C++:

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        for(int i = 0;i < n;i++)
        {
            if(A[i] >= target)
                return i;
        }
        return n;
    }
};

     Python:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        n = len(A)
        for i in range(0,n):
            if A[i] >= target:
                return i
        return n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值