【矩阵】240. 搜索二维矩阵 II【中等】

搜索二维矩阵 II

  • 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。
  • 该矩阵具有以下特性:
  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例 1:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5

输出:true

解题思路

  • 1、根据矩阵的特性,可以发现右上角的元素具有一个特性:它是该行最大的元素,并且是该列最小的元素。
  • 2、我们可以从右上角开始搜索,如果当前元素等于目标值,则返回 true。
  • 3、如果当前元素大于目标值,则目标值必定在当前元素的左侧列,因此向左移动一列。
  • 4、如果当前元素小于目标值,则目标值必定在当前元素的下方行,因此向下移动一行。
  • 5、重复步骤 3 和 4,直到找到目标值或者越界。

Java实现

bash 复制代码
public class Search2DMatrixII {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        int row = 0, col = n - 1; // Start from the top-right corner从右上角开始
//        {1, 4, 7, 11, 15},
//        {2, 5, 8, 12, 19},
//        {3, 6, 9, 16, 22},
//        {10, 13, 14, 17, 24},
//        {18, 21, 23, 26, 30}
        while (row < m && col >= 0) {
            if (matrix[row][col] == target) {
                return true; // Found the target
            } else if (matrix[row][col] > target) {
                col--; // Move left in the current row 在当前行向左移动
            } else {
                row++; // Move down to the next row 向下移动到下一行
            }
        }
        
        return false; // Target not found
    }

    public static void main(String[] args) {
        Search2DMatrixII search = new Search2DMatrixII();
        int[][] matrix = {
            {1, 4, 7, 11, 15},
            {2, 5, 8, 12, 19},
            {3, 6, 9, 16, 22},
            {10, 13, 14, 17, 24},
            {18, 21, 23, 26, 30}
        };
        int target1 = 5;
        int target2 = 20;
        System.out.println("Target 5 found: " + search.searchMatrix(matrix, target1));
        System.out.println("Target 20 found: " + search.searchMatrix(matrix, target2));
    }
}

时间空间复杂度

  • 时间复杂度:O(m + n),其中 m 和 n 分别是矩阵的行数和列数
  • 空间复杂度:O(1),只需要使用常数级别的额外空间
相关推荐
钢铁男儿7 分钟前
C# 接口(接口可以继承接口)
java·算法·c#
肉肉不想干后端32 分钟前
分布式ID:基于K8s-PodName的百度雪花ID生成方案优化
java
zl_vslam1 小时前
SLAM中的非线性优化-2D图优化之激光SLAM cartographer前端匹配(十七)
前端·人工智能·算法
青云交1 小时前
Java 大视界 -- Java 大数据在智能安防视频监控系统中的视频摘要快速生成与检索优化(345)
java·大数据·智能安防·视频摘要·检索优化·校园安防·低带宽传输
geovindu1 小时前
Java: OracleHelper
java·开发语言·oracle
程序员奈斯1 小时前
苍穹外卖—day1
java
ChoSeitaku1 小时前
NO.4数据结构数组和矩阵|一维数组|二维数组|对称矩阵|三角矩阵|三对角矩阵|稀疏矩阵
数据结构·人工智能·矩阵
今天又在摸鱼1 小时前
SpringCloud
java·spring cloud
zqmattack2 小时前
XML外部实体注入与修复方案
java·javascript·安全
dying_man2 小时前
LeetCode--44.通配符匹配
算法·leetcode