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;
    }
    };

从右上角开始查找

相关推荐
辰烨chenye5 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
hqyjzsb8 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术8 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
sanjiaomao3339 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
乐迪信息9 小时前
如何通过AI防爆摄像机精准判断船舶超速?
大数据·人工智能·算法·安全·目标跟踪
大圣编蚕10 小时前
Java ByteArrayInputStream 详解:从入门到实战
java·开发语言·算法
小玮看世界11 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
黎阳之光11 小时前
数字孪生赋能全域水网,实现水资源管控与节水降碳双向提升
人工智能·物联网·算法·安全·数字孪生
随意起个昵称11 小时前
【BFS】冰面滑行
算法·宽度优先