amazon oa1 - search in 2D array II [Leetcode] 240

时间:2021-09-26 03:57:01

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

巧解题,矩阵本身等于了一个binary search tree,从中值开始走

时间复杂度 O(m+n)

public boolean searchMatrix(int[][] matrix, int target) {
  if(matrix.length==0 || matrix[0].length==0) return false;

  int n = matrix.length;
  int m = matrix[0].length;
  int x = n-1;
  int y = 0;
  while( x>=0 && y<m) {
    if (matrix[x][y]==target) {
      return true;
    }
    if (matrix[x][y]< target) {
      y++;
    }
    else {
      x--;
    }
  }
  return false;
}