【Leetcode 热题 100】74. 搜索二维矩阵

问题背景

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

  • 每行中的整数从左到右按非严格递增顺序排列。
  • 每行的第一个整数大于前一行的最后一个整数。
    给你一个整数 t a r g e t target target,如果 t a r g e t target target 在矩阵中,返回 t r u e true true;否则,返回 f a l s e false false。

数据约束

  • m = m a t r i x . l e n g t h m = matrix.length m=matrix.length
  • n = m a t r i x [ i ] . l e n g t h n = matrix[i].length n=matrix[i].length
  • 1 ≤ m , n ≤ 100 1 \le m, n \le 100 1≤m,n≤100
  • − 1 0 4 ≤ m a t r i x [ i ] [ j ] , t a r g e t ≤ 1 0 4 -10 ^ 4 \le matrix[i][j], target \le 10 ^ 4 −104≤matrix[i][j],target≤104

解题过程

题目保证整个矩阵中的元素从上到下从左到右依次递增,也就是可以展开成一个递增的一维数组,可以用下标映射的方式,在这个虚拟的一维矩阵中进行二分搜索,时间复杂度为 O ( l o g ( m n ) ) O(log(mn)) O(log(mn))。

还可以用排除法,参考 搜索二维矩阵 II。从矩阵的右上角开始,每次比较能够去掉一行或一列,相当于查找抽象的二叉搜索树,时间复杂度大致在 O ( m + n ) O(m + n) O(m+n) 这个量级。

具体实现

整体二分

java 复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        int left = 0, right = m * n;
        while(left < right) {
            int mid = left + ((right - left) >>> 1);
            int cur = matrix[mid / n][mid % n];
            if(cur == target) {
                return true;
            }
            if(cur < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return false;
    }
}

查找抽象二叉搜索树

java 复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int i = 0;
        int j = matrix[0].length - 1;
        while(i < matrix.length && j >= 0) {
            int cur = matrix[i][j];
            if(cur == target) {
                return true;
            }
            if(cur < target) {
                i++;
            } else {
                j--;
            }
        }
        return false;
    }
}
相关推荐
ZoeJoy820 分钟前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.25 分钟前
dfs由易到难
算法·蓝桥杯·宽度优先
_日拱一卒37 分钟前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
云泽8081 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享2 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病2 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中3 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy3 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209253 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长4 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv