【LeetCode】剑指 Offer 04. 二维数组中的查找 p44 -- Java Version
题目链接: https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
1. 题目介绍(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
2. 题解
2.1 暴力枚举 – O(nm)
时间复杂度O(nm),空间复杂度O(1)
class Solution {// 暴力枚举public boolean findNumberIn2DArray(int[][] matrix, int target) {// 1. 判断数组是否为空,如果是则返回falseif (matrix.length <= 0) return false;// 2. 定义变量,记录二维数组的行列int n = matrix.length;int m = matrix[0].length;// 3. 循环遍历每一个值,直到找到正确结果for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (matrix[i][j] == target) return true;}}// 4. 循环结束,数组中不存在targetreturn false;}
}
2.2 “标记数”数组剔除 – O(n+m)
时间复杂度O(n+m),空间复杂度O(1)
class Solution {// 标记数数组剔除public boolean findNumberIn2DArray(int[][] matrix, int target) {// 1. 判断数组是否为空,如果是则返回falseif (matrix.length <= 0) return false;// 2. 定义变量,记录二维数组的行列int row = 0, col = matrix[0].length-1;// while (col >= 0 && row < matrix.length){if (matrix[row][col] > target) col--;else if (matrix[row][col] < target) row++;else return true;}// 4. 循环结束,数组中不存在targetreturn false;}
}
3. 思考
没想到,用穷举在力扣的测试用例里面也这么快,感觉还是约束条件太小了。
4. 参考资料
[1] 面试题04. 二维数组中的查找(标志数,清晰图解)