LeetCode hot100-240搜索二维矩阵 II

复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        for (const auto& row: matrix) {
            auto it = lower_bound(row.begin(), row.end(), target);
            if (it != row.end() && *it == target) {
                return true;
            }
        }
        return false;
    }
};
复制代码
auto it = lower_bound(row.begin(), row.end(), target);
  • row:一个有序的 vector(如 vector<int>

  • lower_bound:二分查找算法,返回一个迭代器

  • auto:自动推导迭代器类型

  • it:指向第一个 >= target 的元素

  • 有序数组中查找第一个大于等于 target 的元素。

    class Solution {
    public:
    bool searchMatrix(vector<vector>& matrix, int target) {
    int m = matrix.size(), n = matrix[0].size();
    int x = 0, y = n - 1;
    while (x < m && y >= 0) {
    if (matrix[x][y] == target) {
    return true;
    }
    if (matrix[x][y] > target) {
    --y;
    }
    else {
    ++x;
    }
    }
    return false;
    }
    };

从右上角开始查找

相关推荐
罗西的思考18 小时前
机器人 / 强化学习】HIL-SERL:人类在环驱动的具身智能进化框架
人工智能·算法·机器学习
美团技术团队21 小时前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法
To_OC2 天前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC2 天前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
_清歌2 天前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局2 天前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象2 天前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局2 天前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法