【矩阵】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),只需要使用常数级别的额外空间
相关推荐
hsling松子2 小时前
使用PaddleHub智能生成,献上浓情国庆福
人工智能·算法·机器学习·语言模型·paddlepaddle
dengqingrui1232 小时前
【树形DP】AT_dp_p Independent Set 题解
c++·学习·算法·深度优先·图论·dp
C++忠实粉丝2 小时前
前缀和(8)_矩阵区域和
数据结构·c++·线性代数·算法·矩阵
ZZZ_O^O3 小时前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
CV-King3 小时前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
ok!ko3 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
代码雕刻家3 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
雨中rain3 小时前
算法 | 位运算(哈希思想)
算法
2402_857589364 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰4 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin