74. 搜索二维矩阵

方法一:两次二分查找
cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>> matrix, int target) {
        auto row = upper_bound(matrix.begin(), matrix.end(), target, [](const int b, const vector<int> &a) {
            return b < a[0];
        });
        if (row == matrix.begin()) {
            return false;
        }
        --row;
        return binary_search(row->begin(), row->end(), target);
    }
};

方法二:一次二分查找

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = matrix[0].size();
        int low = 0, high = m * n - 1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            int x = matrix[mid / n][mid % n];
            if (x < target) {
                low = mid + 1;
            } else if (x > target) {
                high = mid - 1;
            } else {
                return true;
            }
        }
        return false;
    }
};

leetcode题解

相关推荐
Jasmine_llq1 天前
《B3865 [GESP202309 二级] 小杨的 X 字矩阵》
线性代数·矩阵·条件判断算法·枚举算法(遍历算法)·规律模拟算法
杰杰桀桀桀1 天前
4*4无时延矩阵键盘(非阻塞)--附代码链接
stm32·单片机·嵌入式硬件·矩阵·计算机外设·无时延矩阵键盘
阿Y加油吧1 天前
二分查找进阶:搜索二维矩阵 & 查找元素首尾位置 深度解析
线性代数·算法·矩阵
songyuc1 天前
【矩阵论】关于rank的几何解释:“观测者维度”
人工智能·矩阵
计算机安禾1 天前
【数据结构与算法】第33篇:交换排序(二):快速排序
c语言·开发语言·数据结构·数据库·算法·矩阵·排序算法
MediaTea2 天前
AI 术语通俗词典:矩阵乘法
人工智能·线性代数·矩阵
AI_零食2 天前
开源鸿蒙跨平台Flutter开发:研究生科研贡献雷达矩阵架构
学习·flutter·ui·华为·矩阵·开源·harmonyos
如竟没有火炬2 天前
搜索二维矩阵
数据结构·python·算法·leetcode·矩阵
6Hzlia2 天前
【Hot 100 刷题计划】 LeetCode 54. 螺旋矩阵 | C++ 模拟法题解
c++·leetcode·矩阵
AI_零食2 天前
开源鸿蒙跨平台Flutter开发:生物力学与力量周期-臂力训练矩阵架构
学习·flutter·ui·华为·矩阵·开源·harmonyos