学习笔记:剑指 Offer 04. 二维数组中的查找

453 阅读2分钟

题目描述

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

题目示例

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

给定 target = 5,返回 true。

给定 target = 20,返回 false。

题目分析

题中给定的数据为二维数组,一种方法是直接遍历数组,找到对应的target返回true,没找到就返回false。 第二个种方法是线性查找,根据二维数组中行和列来一次查找,具体步骤如下:

  • 倒着查找为例,找到第一行的最后一个元素,与target比较,如果比target大,则对应的列的索引减一
  • 如果元素比target小,则列对应的索引不变,行对应的索引加一,因为数据都是递增的,如果当前这一行的最后一个数据都比taget小,那么前面的所有数据都会比target小
  • 如果相等 返回true

代码实现

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var findNumberIn2DArray = function(matrix, target) {
    // 判断边界值,不存在的直接返回false
    if (matrix == null || matrix.length === 0 || matrix[0].length === 0) {
        return false
    }
    let rowIndex = 0; // 第一行
    let colIndex = matrix[rowIndex].length - 1; // 第一行最后一列
    // 行索引不能超出数组的长度,同理,列索引不能为负数,为负数说明不存在了
    while(rowIndex <= matrix.length - 1 && colIndex >= 0) {
        if (matrix[rowIndex][colIndex] < target) {
            rowIndex++
        } else if (matrix[rowIndex][colIndex] > target) {
            colIndex--
        } else if (matrix[rowIndex][colIndex] === target){
            return true
        }
    }
    return false
};

题目来源

LeetCode:剑指 Offer 04. 二维数组中的查找