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;
    }
};
相关推荐
地平线开发者12 小时前
J6B vio scenario sample
算法
BothSavage1 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn1 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽1 天前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说2 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰2 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六2 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程