leetcode hot 100 -搜索二维矩阵

给你一个满足下述两条属性的 m x n 整数矩阵:

  • 每行中的整数从左到右按非严格递增顺序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false

示例 1:

复制代码
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

示例 2:

复制代码
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

代码 二分的两种写法

java 复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // 这是一个在二维矩阵查找目标值的题       target       采用二分,将二维矩阵变成一维
        int x=matrix.length;
        int y=matrix[0].length;
        // 开区间二分
        int l=-1;
        int r=x*y;
        while(l+1<r){
            int mid=(l+r)>>>1;
            int temp=matrix[mid/y][mid%y];
            if(temp==target) return true;
            else{
                if(temp>target){
                    r=mid;
                }
                else{
                    l=mid;
                }
            }
        }
        return false;
        
    }
    //  int l=0;
    //     int r=x*y-1;
    //     //闭区间二分
    //     while(l<=r){
    //        int mid=l+(r-l)/2;
    //        int temp=matrix[mid/y][mid%y];
    //        if(temp==target){
    //         return true;
    //        }
    //        else{  //目标值比现在值大
    //              if(temp>target){
    //                  r=mid-1;
    //              }
    //              else{
    //                  l=mid+1;
    //              }
    //        }
    //     }
    //     return false;
}
相关推荐
ValhallaCoder5 小时前
hot100-堆
数据结构·python·算法·
小小小米粒5 小时前
函数式接口 + Lambda = 方法逻辑的 “插拔式解耦”
开发语言·python·算法
风吹乱了我的头发~6 小时前
Day31:2026年2月21日打卡
开发语言·c++·算法
望舒5136 小时前
代码随想录day33,动态规划part2
java·算法·leetcode·动态规划
那起舞的日子7 小时前
牛客网刷算法的启发
算法
追随者永远是胜利者7 小时前
(LeetCode-Hot100)169. 多数元素
java·算法·leetcode·go
s砚山s7 小时前
代码随想录刷题——二叉树篇(二十)
算法
-Rane8 小时前
【C++】vector
开发语言·c++·算法
代码栈上的思考8 小时前
滑动窗口算法实战
算法
Eloudy8 小时前
直接法 读书笔记 06 第6章 LU分解
人工智能·算法·ai·hpc