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;
    }
};
相关推荐
一个不知名程序员www18 分钟前
算法学习入门---模拟(C++)
c++·算法
搂鱼11451429 分钟前
GJOI 11.10 题解
算法
爱睡觉的咋33 分钟前
openGauss × AI:打造一个能识图、能讲解、还能推荐的智慧博物馆导览师
算法
视觉AI1 小时前
一帧就能“训练”的目标跟踪算法:通俗理解 KCF 的训练机制
人工智能·算法·目标跟踪
2301_795167201 小时前
玩转Rust高级应用 如何理解 Rust 实现免疫数据竞争的关键是Send 和 Sync 这两个 trait
开发语言·算法·rust
Blossom.1181 小时前
AI Agent记忆系统深度实现:从短期记忆到长期人格的演进
人工智能·python·深度学习·算法·决策树·机器学习·copilot
贩卖黄昏的熊1 小时前
数据结构示例代码
数据结构
Q741_1472 小时前
C++ 面试高频考点 链表 迭代 递归 力扣 25. K 个一组翻转链表 每日一题 题解
c++·算法·链表·面试·递归·迭代
_fairyland2 小时前
数据结构 力扣 练习
数据结构·考研·算法·leetcode
Neil今天也要学习3 小时前
永磁同步电机无速度算法--基于三阶LESO的反电动势观测器
算法·1024程序员节