LeetCode - 240. Search a 2D Matrix II

来源:互联网 发布:it解决方案供应商 编辑:程序博客网 时间:2024/06/11 16:58

矩阵中两行或者两列之间的元素的大小并没有一定的规律,所以二分法不太好用,直接用74. Search a 2D Matrix的解法二即可,时间复杂度为O(n + m),代码如下:

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


0 0
原创粉丝点击