【矩阵】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),只需要使用常数级别的额外空间
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值