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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    导航栏下拉至一定高度后固定在顶部的特效
    laravel表单中文错误提示本地化
    laravel模板使用
    网站测试用例
    sublime安装ctags用于追踪函数
    ecshop头部添加所在城市
    php 常用的redis操作语法
    mysql where与 having的区别
    mysql 列类型以及属性特点
    不错的博客链接
  • 原文地址:https://www.cnblogs.com/itdef/p/14569339.html
Copyright © 2011-2022 走看看