剑指 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 - 1
,y
设置为 0,如果元素等于 target
直接返会 true
,如果元素大小 target
则 x—
,如果元素小于 taget
则 y++
,直到越数组边界未找到,返回 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;
}
}
5 条评论
作者的才华横溢,让这篇文章成为了一篇不可多得的艺术品。
独特的构思和新颖的观点,让这篇文章在众多作品中脱颖而出。
建议标注关键步骤的注意事项。
123
1231313