【leetcode】35. Search Insert Position

Difficulty:medium

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

解题思路:

这道题目是二分搜索的应用,相比较与简单的二分搜索,这个题目要求在找到target时返回index,并且如果没有找到的时候要返回按照大小顺序需要插入元素的位置的index.

那么首先进行一遍二分搜索,如果在二分搜索的过程中找到了matrix[mid]=target,这时直接返回mid作为index。

其次考虑,如果没有找到target,那么在跳出while(left<=right)循环时,由于在循环内部每一次都是控制left=mid+1,right=mid-1,当left+1=right进入循环时,那么mid=left,这时通过判断,改变后left=right,再次进行循环,这时,target!=matrix[mid]的情况下,要么是使left+1,要么是right-1,经过判断都是使left=right+1。

当循环结束,如果在上一步中是由于matrix[mid]<target引起的left+1,那么说明需要返回mid+1位置的index,如果是matrix[mid]>target引起的right-1,这时left的值没有改变,需要返回mid的值就是要插入的值。但是无论哪种情况,都保证了返回的值都恰好等于left的值,所以最后直接返回left即可。

代码如下:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值