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题解

相关推荐
YuTaoShao16 分钟前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵
打螺丝否11 小时前
稠密矩阵和稀疏矩阵的对比
python·机器学习·矩阵
人机与认知实验室11 小时前
人机环境系统智能矩阵理论
线性代数·矩阵
fFee-ops2 天前
73. 矩阵置零
线性代数·矩阵
星逝*2 天前
LeetCode刷题-top100( 矩阵置零)
算法·leetcode·矩阵
码界奇点2 天前
豆包新模型矩阵与PromptPilot构建企业级AI开发的体系化解决方案
人工智能·线性代数·ai·语言模型·矩阵·硬件工程
酸奶乳酪2 天前
矩阵和向量的双重视角
线性代数·矩阵
阿维的博客日记2 天前
LeetCode 240: 搜索二维矩阵 II - 算法详解(秒懂系列
算法·leetcode·矩阵
桐果云3 天前
解锁桐果云零代码数据平台能力矩阵——赋能零售行业数字化转型新动能
大数据·人工智能·矩阵·数据挖掘·数据分析·零售
自信的小螺丝钉3 天前
Leetcode 240. 搜索二维矩阵 II 矩阵 / 二分
算法·leetcode·矩阵