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

从右上角开始查找

相关推荐
怪奇云呼军几秒前
闪电智能 Voice Agent 怎样根据语速、停顿和追问方式切换话术?策略引擎拆解
开发语言·人工智能·网络协议·算法·语音识别·web app
稚南城才子,乌衣巷风流4 分钟前
树链剖分(树剖)算法详解:从原理到实现
算法·深度优先
jz_ddk14 分钟前
[信号处理] 数学与工程之美:相邻差分共轭乘积
数学·算法·信号处理·差分·共轭
m沐沐9 小时前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b9 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu9 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
Zachery Pole11 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米11 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星830357712 小时前
【算法】最长递增子序列(三种解法)
算法
啦啦啦啦啦zzzz12 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法