/**
* 暴力枚举法
* 时间复杂度:O(m * n)
* 空间复杂度:O(1)
*/
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for (int[] ints : matrix) {
for (int anInt : ints) {
if (anInt == target)
return true;
}
}
return false;
}
}
/**
* 优化后的算法
* 时间复杂度:O(m + n)
* 空间复杂度:O(1)
*/
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = 0;
int col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
}
以上是两个不同算法的 Java 代码,用于在一个二维数组中查找目标数字。
第一个算法是暴力枚举法,它的时间复杂度为 O(m * n),其中 m 和 n 分别为矩阵的行数和列数。
第二个算法是优化后的算法,它的时间复杂度为 O(m + n),空间复杂度为 O(1)。
优化后的算法基于矩阵的特殊性质,从矩阵的右上角或左下角开始查找,依次排除行或列,直到找到目标数字或者查找完所有数字。