剑指 Offer 04. 二维数组中的查找(Javascript)

37 阅读1分钟
/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var findNumberIn2DArray = function (matrix, target) {
  // row 行数 col 列数
  if (!matrix.length) return false
  let row1 = 0,
    row2 = matrix.length - 1,
    col1 = 0,
    col2 = matrix[0].length - 1
  while (row1 <= row2 && col1 <= col2) {
    if (matrix[row2][col1] == target) return true
    if (row1 == row2 && col1 == col2) return false
    while (target < matrix[row2][col1] && row2 > row1) row2--
    while (target < matrix[row1][col2] && col2 > col1) col2--
    while (target > matrix[row1][col2] && row1 < row2) row1++
    while (target > matrix[row2][col1] && col1 < col2) col1++
  }
  return false
}