35. Search Insert Position

本文介绍了一种在已排序数组中查找目标值的方法,并提供了两种实现方式:直接遍历法和二分查找法。直接遍历法易于理解,而二分查找法则更高效。

1,题目要求
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.
这里写图片描述
对一个已经进行排序的数组中寻找目标值,如果找到了就返回对应的index,否则就返回target应该在位置的index。

2,题目思路
直接进行遍历查找就可以实现,或者利用二分查找的思想。

3,程序源码
直接法:(8ms)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i] >= target )
                return i;
        }
        return nums.size();
    }
};

二分查找法:(7ms)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0, high = nums.size()-1;
        while(low<=high)
        {
            int mid = low + (high - low)/2;
            if(target == nums[mid])
                return mid;
            else if(target>nums[mid])
                low = mid+1;                
            else
                high = mid-1;
        }
        return low; 
    }
};

当while循环完成时,说明没有找到对应的数字,此时low > high,即low = high+1。因为数字树位于[low, hight+1]中的,也即位于[low,low]之中,因此返回low,即为target的最后的位置。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值