【leetcode-74】搜索二维矩阵

(较简单,但犯错太多)

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

示例 1:

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true

示例 2:

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
输出: false

我的:二分,不难但下标转换调试很久
执行用时 : 1 ms, 在Search a 2D Matrix的Java提交中击败了100.00% 的用户
内存消耗 : 44.6 MB, 在Search a 2D Matrix的Java提交中击败了0.61% 的用户
    public boolean searchMatrix(int[][] matrix, int target) {
        // 实际遇到其实可以遍历放到数组中二分,这样很简单且题目并没额外要求
        // 数组容易忽略不为空但是为[]的情况所以要判断matrix.length != 0
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int end = row*col-1;
        int start = 0;
        while (start <= end) {
            int mid = (start + end)/2;
            int val = matrix[mid/col][mid%col];  //0-end数组下标转矩阵下标就是这么简洁,想复杂了
            if (val == target) {
                return true;
            } else if (val < target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return false;
    }

 

参考解法:比二分慢些但是逻辑简单啊

执行用时 : 2 ms, 在Search a 2D Matrix的Java提交中击败了100.00% 的用户
内存消耗 : 41.4 MB, 在Search a 2D Matrix的Java提交中击败了0.61% 的用户

首先选取右上角数字,如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,去掉此数字所在列;如果该数字小于要查找的数字,则去掉该数字所在行。重复上述过程直到找到要查找的数字,或者查找范围为空。
public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0)
            return false;
        int row = 0, col = matrix[0].length-1;
        while(row < matrix.length && col >= 0){
            if(matrix[row][col] < target)
                row++;
            else if(matrix[row][col] > target)
                col--;
            else
                return true;
        }
        return false;
    }

 

 

 

 

posted @ 2019-04-03 09:53  twoheads  阅读(163)  评论(0编辑  收藏  举报