70 搜索插入位置

搜索插入位置

    • [题解1 二分查找](#题解1 二分查找)
    • [题解2 STL大法](#题解2 STL大法)

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

请必须使用时间复杂度为 O ( l o g n ) O(log n) O(logn)的算法。

示例 1:

输入: nums = [1,3,5,6], target = 5

输出: 2

示例 2:

输入: nums = [1,3,5,6], target = 2

输出: 1

示例 3:

输入: nums = [1,3,5,6], target = 7

输出: 4

提示:

  • 1 <= nums.length <= 1 0 4 10^4 104
  • − 1 0 4 -10^4 −104 <= nums[i] <= 1 0 4 10^4 104
  • nums无重复元素升序 排列数组
  • − 1 0 4 -10^4 −104 <= target <= 1 0 4 10^4 104

题解1 二分查找

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int len = nums.size();
        int left = 0;
        int right = len-1;
        int pos = 0;
        while(left <= right){
            int mid = (left+right) >> 1;
            if(nums[mid] == target) return mid;
            else if(nums[mid] < target){
                left = mid+1;
                // left就是升序情况下 应该插入的位置
                pos = left;
            }else{
                right = mid-1;
            }
        }
        return pos;
    }
};


防越界写法

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int left = 0, right = n - 1, ans = n;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;
            if (target <= nums[mid]) {
            // mid = left + (difference)>>1 (Key: 找到第一个下标,对应值 >= target)
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
};

题解2 STL大法

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        auto it = find(nums.begin(),nums.end(),target);
        if(it!=nums.end()){
            return it-nums.begin();
        }
        auto first =lower_bound(nums.begin(), nums.end(), target);
        return first-nums.begin();
    }
};

两行

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        auto st = nums.cbegin(), ed = nums.cend();
        return lower_bound(st, ed, target) - st;
    }
};
相关推荐
想做小南娘,发现自己是女生喵1 小时前
【无标题】
数据结构·算法
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎3 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀4 小时前
约瑟夫环问题
算法
凤凰院凶涛QAQ5 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
科技大视界6 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴6 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe6 小时前
算法滑动窗口
数据结构·算法
怪兽学LLM6 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展