leetcode [240] Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following 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]
]

Given target = 5, return true.

Given target = 20, return false.

题目大意:

在二维数组中找寻指定的数字是否存在,数组从左到右递增,数组从上到下递增。

解法:

我想的是一行一行的寻找,如果说行开头的数字大于目标数字,那么说明目标数在数组中不存在,返回false,如果行结尾的数字小于目标数,说明该行没有目标数字,到下一行去寻找,否则就对该行进行二分查找。

class Solution {
    private boolean find(int[][] matrix,int i,int target){
        int left=0,right=matrix[0].length-1;
        while(left<=right){
            int mid=(left+right)/2;
            if (matrix[i][mid]==target) return true;
            else if (matrix[i][mid]<target)  left=mid+1;
            else right=mid-1;
        }
        return false;
    }

    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length==0 || matrix[0].length==0) return false;
        int m=matrix.length,n=matrix[0].length;
        if (target<matrix[0][0]||target>matrix[m-1][n-1]) return false;
        for(int i=0;i<m;i++){
            if (matrix[i][0]>target) return false;
            if (matrix[i][n-1]<target) continue;
            if (find(matrix,i,target)){
                return true;
            }
        }
        return false;
    }
}

 从数组的右上角开始寻找,这么简单的题目,我竟然给忘记了。

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

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/10833686.html