网站建设注册名有规范吗,上海南站网站建设公司,制作团体网站,小蓝鸟加速器【问题描述】[中等]
在一个 n * m 的二维数组中#xff0c;每一行都按照从左到右递增的顺序排序#xff0c;每一列都按照从上到下递增的顺序排序。请完成一个函数#xff0c;输入这样的一个二维数组和一个整数#xff0c;判断数组中是否含有该整数。示例:现有矩阵 matrix …【问题描述】[中等]
在一个 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。
【解答思路】
1. 暴力
时间复杂度O(N*M) 空间复杂度O(1)
class Solution {public boolean findNumberIn2DArray(int[][] matrix, int target) {if (matrix null || matrix.length 0 || matrix[0].length 0) {return false;}int rows matrix.length, columns matrix[0].length;for (int i 0; i rows; i) {for (int j 0; j columns; j) {if (matrix[i][j] target) {return true;}}}return false;}
}
2. 标志数 时间复杂度O(NM) 空间复杂度O(1)
class Solution {public boolean findNumberIn2DArray(int[][] matrix, int target) {int i matrix.length - 1, j 0;while(i 0 j matrix[0].length){if(matrix[i][j] target) i--;else if(matrix[i][j] target) j;else return true;}return false;}
}
【总结】
1.二维数组行列[行][列]
int rows matrix.length,;
int columns matrix[0].length;2. 标志大法好
转载链接https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/solution/mian-shi-ti-04-er-wei-shu-zu-zhong-de-cha-zhao-zuo/