Loading...

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

在一个 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 = 5,返回 true

给定 target = 20,返回 false

限制:

0 <= n <= 1000

0 <= m <= 1000

题解 1 - 从左下角找

从左下角看,上方的数据都比下方的小,右侧的数据都比左侧的大。

设行数为 rows,列数为 columns

从左下角找,所以 x 设为 columns - 1y 设置为 0,如果元素等于 target 直接返会 true,如果元素大小 targetx—,如果元素小于 tagety++,直到越数组边界未找到,返回 false.

class Solution { public boolean findNumberIn2DArray(int[][] matrix, int target) { int rows = matrix.length; if (rows == 0) { return false; } int columns = matrix[0].length; int x = rows - 1, y = 0; while (x >= 0 && y <= columns - 1) { int n = matrix[x][y]; if (n == target) { return true; } else if (n > target) { x--; } else { y++; } } return false; } }

题解 2 — 从右上角找

和题解 1 思路差不多,只是反过来而已

class Solution { public boolean findNumberIn2DArray(int[][] matrix, int target) { int rows = matrix.length; if (rows == 0) { return false; } int columns = matrix[0].length; int x = 0, y = columns - 1; while (x <= rows - 1 && y >= 0) { int n = matrix[x][y]; if (n == target) { return true; } else if (n > target) { y--; } else { x++; } } return false; } }
最后修改:2022 年 10 月 07 日
如果觉得我的文章对你有用,请我喝杯咖啡吧。