Skip to content

Latest commit

 

History

History
43 lines (35 loc) · 1.09 KB

04. 二维数组中的查找.md

File metadata and controls

43 lines (35 loc) · 1.09 KB

题目链接:

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

思路:

类似二分查找的做法:

  1. 左下角开始寻找,因为左下角的元素是当前行最小的、当前列最大的
  2. 比较元素,如果太大了,上移一行
  3. 如果太小了,右移一列
  4. 找到就返回true
  5. 遍历完,返回false

代码:

JavaScript

const findNumberIn2DArray = (matrix, target) => {
    const [m, n] = [matrix.length, matrix[0]?.length];
    if (!m) return false;
    // 定义左下角的坐标
    let [row, col] = [m - 1, 0];
    // 坐标在矩阵内,就一直寻找
    while (row >= 0 && col <= n - 1) {
        // 当前元素
        const item = matrix[row][col];
        if (item === target) {
            // 找到,返回true
            return true;
        } else if (item > target) {
            // 太大了,上移一行
            row--;
        } else {
            // 太小了,右移一列
            col++;
        }
    }
    return false;
};