leetcode 35. 搜索插入位置

题目:35. 搜索插入位置 - 力扣(LeetCode)

加班刷水题

cpp 复制代码
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if (target <= nums[0]) return 0;
        if (target > nums[nums.size() - 1]) return nums.size();
        int l = 0;
        int r = nums.size() - 1;
        while (l <= r) {
            int m = (l + r) / 2;
            if (target == nums[m]) return m;
            if (target > nums[m]) {
                if (target < nums[m + 1]) return m + 1;
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        return -1;
    }
};
相关推荐
海石11 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石11 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
tachibana21 天前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
不能跑的代码不是好代码1 天前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特1 天前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
YuK.W2 天前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
旖-旎2 天前
《LeetCode 64 最小路径和 || LeetCode 174 地下城游戏》
c++·算法·leetcode·动态规划
凯瑟琳.奥古斯特2 天前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
凯瑟琳.奥古斯特2 天前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111112 天前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表