如何做外贸品牌网站建设,德阳 网站建设,泉州模板建站公司,wordpress 商品列表题目链接#xff1a; https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
1. 题目介绍#xff08;04. 二维数组中的查找#xff09; 在一个 n * m 的二维数组中#xff0c;每一行都按照从左到右 非递减 的顺序排序#xff0c;每一列都按照从上到下 非递…题目链接 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(nm)
时间复杂度O(nm)空间复杂度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. 二维数组中的查找标志数清晰图解