Leetcode 35. 搜索插入位置 二分查找

地址  https://leetcode-cn.com/problems/search-insert-position/

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:
输入: [1,3,5,6], 5
输出: 2

示例 2:
输入: [1,3,5,6], 2
输出: 1

示例 3:
输入: [1,3,5,6], 7
输出: 4

示例 4:
输入: [1,3,5,6], 0
输出: 0

解答 二分模板题目

注意两种二分模板分别查找的是 target在数组中的上边界和下边界 要稍做调整

class Solution {
public:
    
    bool Check(const vector<int>& nums,int idx, int target){
        return nums[idx] >= target;
    }
    
    int searchInsert(vector<int>& nums, int target) {
        int l= 0; int r = nums.size()-1;
        while(l < r){
            int mid = (l+r)>>1;
            if(Check(nums,mid,target)) r= mid;
            else l =mid+1;
        }
        if(nums[l] < target) return l+1;
        return l;
    }
};

 

posted on 2021-03-23 12:57  itdef  阅读(36)  评论(0编辑  收藏  举报

导航