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

相关推荐
太妃糖耶8 小时前
URP-利用矩阵在Shader中实现物体的平移和缩放
unity·矩阵
优美的赫蒂1 天前
理解欧拉公式
线性代数·算法·数学建模
岩中竹1 天前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
byxdaz1 天前
矩阵运算和线性代数操作开源库
矩阵
User_芊芊君子1 天前
【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
c语言·算法·矩阵
weixin_428498491 天前
使用HYPRE库并行装配IJ稀疏矩阵
线性代数·矩阵
THe CHallEnge of THe BrAve2 天前
工业相机中CCM使能参数-色彩校正矩阵
数码相机·线性代数·矩阵
小美爱刷题2 天前
力扣DAY63-67 | 热100 | 二分:搜索插入位置、搜索二维矩阵、排序数组查找元素、搜索旋转排序数组、搜索最小值
算法·leetcode·矩阵
NorthFish北海有鱼2 天前
python三维矩阵的维度
python·矩阵·numpy
该怎么办呢3 天前
webgl入门实例-11模型矩阵 (Model Matrix)基本概念
线性代数·矩阵·webgl