74 Search a 2D Matrix

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

Write an efficient algorithm that searches for a value in anmxnmatrix. 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.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Giventarget=3, returntrue.

分析及代码

方法一

自己的做法,先搜行,后搜列,两次二分

注意的是,搜行的是如果小于格子里任意一个数,会返回-1行,会导致错误,和0比较一下

public boolean searchMatrix(int[][] matrix, int target) {
    if(matrix.length == 0 || matrix[0].length == 0) {
        return false;
    }
    int row = matrix.length;
    int col = matrix[0].length;
    int l = 0;
    int r = row - 1;
    while(l <= r) {
        int mid = l + (r - l) / 2;
        if(matrix[mid][0] == target) {
            return true;
        } else if(matrix[mid][0] < target) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    int targetRow = Math.max(l - 1, 0);
    l = 0;
    r = col - 1;
    while(l <= r) {
        int mid = l + (r - l) / 2;
        if(matrix[targetRow][mid] == target) {
            return true;
        } else if(matrix[targetRow][mid] < target) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    return false;
}

方法二

因为第一行最后一个数也是小于第二行第一个的,所以可以整个表格拼接成一个排好序的list

public boolean searchMatrix(int[][] matrix, int target) {
    if(matrix.length == 0 || matrix[0].length == 0) {
        return false;
    }
    int row = matrix.length;
    int col = matrix[0].length;
    int total = row * col;
    int l = 0;
    int r = total - 1;
    while(l <= r) {
        int mid = l + (r - l) / 2;
        int rowMid = mid / col;
        int colMid = mid % col;
        if(matrix[rowMid][colMid] == target) {
            return true;
        } else if(matrix[rowMid][colMid] < target) {
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    return false;
}

O(logmn)

results matching ""

    No results matching ""