Leetcode 240. 搜索二维矩阵 II 矩阵 / 二分

原题链接: Leetcode 240. 搜索二维矩阵 II


解法一:排除法

参考 【图解】排除法,一图秒懂!(Python/Java/C++/C/Go/JS/Rust)

从右上角:

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m=matrix.size();
        int n=matrix[0].size();
        int min_num=matrix[0][0];
        int max_num=matrix[m-1][n-1];
        if(target<min_num || target>max_num) return false;
        int i=0,j=n-1;
        while(i<m && j>=0){
            if( matrix[i][j]==target) {
                return true;
            }
            if( matrix[i][j]<target){
                i++;
            }
            else{
                j--;
            }
        }
        return false;
    }
};

从左下角:

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m=matrix.size();
        int n=matrix[0].size();
        int min_num=matrix[0][0];
        int max_num=matrix[m-1][n-1];
        if(target<min_num || target>max_num) return false;
        int i=m-1,j=0;
        while(i>=0 && j<n){
            if( matrix[i][j]<target ){
                j++;
            }
            else if( matrix[i][j]>target ){
                i--;
            }
            else return true;
        }
        return false;
    }
};

解法二:二分

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m=matrix.size();
        int n=matrix[0].size();
        int min_num=matrix[0][0];
        int max_num=matrix[m-1][n-1];
        if(target<min_num || target>max_num) return false;
        for(auto row: matrix){
            auto it = lower_bound(row.begin(),row.end(),target);
            if (it != row.end() && *it==target) return true;
        }
        return false;
    }
};
相关推荐
旖-旎2 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC2 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn3 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹4 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术4 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber7 小时前
检索技术的实际应用
人工智能·算法
hhzz7 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_8 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI8 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅