zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    IDEA下同时使用Git和svn
    IDEA进行activiti-archetype-unittest脚手架的安装
    正则表达式
    关于JS堆栈与拷贝
    按值传递--
    JS---变量、作用域和内存问题
    laod
    待解决
    闭包2
    闭包1
  • 原文地址:https://www.cnblogs.com/itdef/p/14569339.html
Copyright © 2011-2022 走看看