leetcode 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.

中文理解:给出一个排序的数组和一个指定的值,数组没有重复元素,如果该值在数组中,则返回该值的下标,如果该值不存在数组中,则返回该值在数组中应该插入的下标。

解题思路:由于数组是排序的,解法一,直接一遍遍历数组,若找到某一个值与该值相等返回这个下标,如果遇到第一个大于该值的值,返回该值的下标;解法二,典型的折半查找,设置start,mid,end来每次进行折半筛选,最后返回start的值即为结果。

代码(java):

class Solution {
    public int searchInsert(int[] nums, int target) {
        int start=0;
        int end=nums.length-1;
        int mid=(start+end)/2;
        while(start<=end){
            if(target<nums[mid]){
                end=mid-1;
            }
            else if(target>nums[mid]){
                start=mid+1;
            }
            else if(target==nums[mid]){
                return mid;
            }
            mid=(start+end)/2;
        }
        return start;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值