LeetCode 74 _ Search a 2D Matrix 在二维矩阵中寻找指定数字是否存在

Description:

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 from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

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

Example 2:

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

 

 

Solution:

 这道题让我们判断在二位数组中是否存在它所给的数

 

看到这种让我们从有序的所有数中找出某数的题目,就是使用二分法来简化。

将二维数组可以看成是两类,首先根据第一列的值,找出target所在的行,例如Example 2中,10<13<23,通过二分法获得13应在第2行中,然后继续使用二分法确定最接近13的数的位置。

最后得到位置以后,将该处的数与target相比,相等即为存在该数,否则不存在。

 

 

Code:

public boolean searchMatrix(int[][] matrix, int target) {

    if (matrix.length == 0 || matrix[0].length == 0){
        return false;
    }

    int row = matrix.length, col = matrix[0].length;
    if (target < matrix[0][0] || target > matrix[row-1][col-1]){
        return false;
    }

    int top = 0, down = row;
    while(top < down){
        int midRow = top + (down - top) / 2;
        if (matrix[midRow][0] <= target){
            top = midRow+1;
        }else{
            down = midRow;  
        }
    }

    int left = 0, right = col;
    while (left < right){
        int midCol = left + (right - left) / 2;
        if (matrix[top-1][midCol] <= target){
            left = midCol+1;
        }else{
            right = midCol;
        }
    }

    if (matrix[top-1][left-1] == target){
        return true;
    }else{
        return false;
    }

}

  

 

提交情况:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Search a 2D Matrix.
Memory Usage: 39.6 MB, less than 20.55% of Java online submissions for Search a 2D Matrix.

posted @ 2019-04-11 20:52  Doris7  阅读(229)  评论(0编辑  收藏  举报