Leet Code 74 Search a 2D Matrix

写一个高效的算法,在 m × n 的二维矩阵中搜索一个值。矩阵有以下性质:

每一行从左到右为升序。

每一行的第一个数都比上一行最后一个数大。

例如,有以下矩阵:

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

给定 target = 3,返回 true。

思路:二分法,目标值与 (m/2,n/2) 位置的值比较,如果相等则返回true,如果目标值小,则搜索矩阵中小于 (m/2,n/2) 的部分,否则搜索矩阵中大于 (m/2,n/2) 的部分。

public class Solution {
  public static boolean searchMatrix(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
      return false;
    }
    return searchMatrix(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1,
        target);
  }

  private static boolean searchMatrix(int[][] matrix, int top, int left,
      int bottom, int right, int target) {
    if (top == bottom && left == right) {
      return matrix[top][left] == target;
    }
    int row = (top + bottom) >> 1;
    int col = (left + right) >> 1;
    if (matrix[row][col] < target) {
      if (row + 1 <= bottom) {
        if (searchMatrix(matrix, row + 1, left, bottom, col, target)) {
          return true;
        }
      }
      if (col + 1 <= right) {
        if (searchMatrix(matrix, row, col + 1, bottom, right, target)) {
          return true;
        }
      }
      return false;
    } else if (matrix[row][col] > target) {
      if (col - 1 >= left) {
        if (searchMatrix(matrix, top, left, row, col - 1, target)) {
          return true;
        }
      }
      if (row - 1 >= top) {
        return searchMatrix(matrix, top, col, row - 1, right, target);
      } else {
        return false;
      }
    } else {
      return true;
    }
  }

}

评论

暂无评论