剑指 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 =
20
,返回false
数据限制:
0 <= n <= 1000
0 <= m <= 1000
解法一:
思路:直接遍历数组
时间复杂度:O(nm)
空间复杂度:O(1)
代码:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
if (matrix[i][j] == target){
return true;
}
}
}
return false;
}
}
解放二:
思路:二分
对数组的每一行进行遍历,由于数组的每一行都递增排序,可以使用二分的方式查找数组中的是否存在target,如果存在则返回true,如果不存在,就遍历下一行,如果遍历完行还是没有找到target,就返回false
解题步骤:
-
对每一行进行遍历
-
将每一行的数据当成一维数组,使用二分查找的思想,查找target是否存在数组中,若存在,则返回true
-
查找完之后,如果没有退出程序,就说明没有找到,返回一个false即可
时间复杂度:O(n㏒₂m)
空间复杂度:O(1)
代码:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++){
int l = 0, r = matrix[i].length - 1;
while (l <= r){
int mid = (l + r) >> 1;
if (matrix[i][mid] > target){
r = mid - 1;
}else if (matrix[i][mid] < target){
l = mid + 1;
}else{
return true;
}
}
}
return false;
}
}
解放三:
思路:
观察题目数据,可以得知:从右上角的方向往左下角看,整个二维数组可以看做是一颗树,树中的节点严格遵守 大于左儿子,小于右儿子 的规则。根据这个规则,可以将二维矩阵类似成二叉搜索树。以右上角的节点为根,判断和target的带下关系,如果大于,则走向左儿子,反之走向右儿子
解题步骤:
-
设置两个下标索引 l 和 r,表示矩阵最右上角的下标,l 初始化为0,r初始化为 matrix[0].length - 1
-
开始进行循环判断,当下标不超出矩阵范围时,判断和target的大小
-
若等于,直接返回true
-
若大于,查找左儿子的数字,表示为 r--
-
若小于,查找右儿子的数字,表示为 l++
-
-
如果最后没有找到target,则返回false
时间复杂度:O(n+m)
空间复杂度:O(1)
代码:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix.length == 0) return false;
int l = 0, r = matrix[0].length - 1;
while (l < matrix.length && r >= 0){
if (matrix[l][r] == target){
return true;
}else if (matrix[l][r] > target){
r--;
}else{
l++;
}
}
return false;
}
}