【Leetcode】240. Search a 2D Matrix II

拟墨画扇 提交于 2020-01-12 20:07:41

题目地址:

https://leetcode.com/problems/search-a-2d-matrix-ii/

给定一个矩阵,满足每行都是单调增的,每列也是单调增的。另给定一个数,问该矩阵是否包含这个数。基本思路是,选定矩阵最左下角的那个数aa,如果targettargetaa大,由于aa所在列在aa上方的数都比aa小,所以不用再搜索,那就向aa的右边走一步;如果targettargetaa小,由于aa所在行在aa右边的数都比aa大,所以不用再搜索,那就向aa的上边走一步。如此这般,直到整个矩阵搜索完毕。
例如,我们要在下面的矩阵里搜索55
[14711152581219369162210131417241821232630]\begin{bmatrix} 1 & 4 & 7 & 11 & 15\\ 2 & \textbf{5} & 8 & 12 & 19\\ \textbf{3} & \textbf{6} & 9 & 16 & 22\\ \textbf{10} & 13 & 14 & 17 & 24\\ \textbf{18} & 21 & 23 & 26 & 30 \end{bmatrix}
路径是:181036518\rightarrow 10 \rightarrow 3 \rightarrow 6 \rightarrow 5

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        
        int x = matrix.length - 1;
        int y = 0;
        while (x >= 0 && y < matrix[0].length) {
            if (matrix[x][y] < target) {
                y++;
            } else if (matrix[x][y] > target) {
                x--;
            } else {
                return true;
            }
        }
        
        return false;
    }
}

时间复杂度O(n)O(n)nn为矩阵元素个数。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!