【矩阵】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实现

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),只需要使用常数级别的额外空间

相关推荐

  1. 矩阵240.搜索矩阵II

    2024-03-16 05:30:04       41 阅读
  2. 240. 搜索矩阵 II

    2024-03-16 05:30:04       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-16 05:30:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-16 05:30:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-16 05:30:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-16 05:30:04       20 阅读

热门阅读

  1. 24计算机考研调剂 | 太原科技大学

    2024-03-16 05:30:04       21 阅读
  2. 【MySQL】mysqladmin、mysqlshow、mysqlcheck都是干嘛的?

    2024-03-16 05:30:04       21 阅读
  3. 【CSS】前端开发中的常见CSS样式问题解决方案

    2024-03-16 05:30:04       20 阅读
  4. 【构建工具】PostCSS快速配置

    2024-03-16 05:30:04       20 阅读
  5. HTML-DAY1

    2024-03-16 05:30:04       16 阅读
  6. C++(1): std::vector的使用

    2024-03-16 05:30:04       21 阅读
  7. 【 React 】对React refs的理解?应用场景?

    2024-03-16 05:30:04       21 阅读
  8. hcie数通和云计算选哪个好?

    2024-03-16 05:30:04       21 阅读