【怒撕剑指Offer】系列旨在用最通俗易懂的语言与动画讲解算法,培养逻辑思维,让你在互联网面试过程中不再畏惧手撕算法。
1 题目描述
在一个 n * m
的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[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。
2 解题思路
从题目中可知,二维数组从左到右是递增的,从上到下也是递增的,那么如果我们从右上角作为起点,向左下方去找的话,就构成了一种二分结构,从图中可以看出,从右向左是递减的,从上到下是递增的,由此可得出三种情况:
- 目标值 > 当前值:接着向下找;
- 目标值 < 当前值:接着向左找;
- 目标值 = 当前值:数组中包含该整数,直接返回。
![](https://i-blog.csdnimg.cn/blog_migrate/b52a4fdf00e819c52c289978924c45ed.png)
3 动图演示
![](https://i-blog.csdnimg.cn/blog_migrate/1352695fae5e769256117326f0205903.gif)
4 代码
4.1 Java
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int i = 0, j = matrix[0].length - 1;
while (i < matrix.length && j >= 0) {
if (matrix[i][j] == target) {
return true;
}
if (target > matrix[i][j]) {
i++;
} else {
j--;
}
}
return false;
}
4.2 Go
func findNumberIn2DArray(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
rows := 0
cols := len(matrix[0])-1
for rows < len(matrix) && cols >=0 {
if matrix[rows][cols] < target {
rows++
} else if matrix[rows][cols] > target{
cols--
} else {
return true
}
}
return false
}
5 链接
![](https://i-blog.csdnimg.cn/blog_migrate/0a118a9cf2b63c97c04a43afe3599e9a.jpeg)