在一个 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。
- 题解
class Solution {
//方法1:暴力解法,直接遍历一层一层遍历
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix==null||matrix.length==0||matrix[0].length==0){
return false;
}
for (int i = 0; i < matrix.length; i++) {//matrix.length是二维数组的长度,即int[size][]里的size
for (int j = 0; j < matrix[0].length; j++) {//matrix[0].length是二维数组的宽度,即int[][size]里的size
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
//方法2
public static boolean findNumberIn2DArray2(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
//根据矩阵的特点,可以先从矩阵的第一行的右边开始查找,先看是否相等
// 再看元素是否大于target,大于target的就往左移动查找
//如果小于target就往下查找
//查找无就继续往左往下查找
int rows = matrix.length;
int column = matrix[0].length - 1;
for (int j = column; j >= 0; j--) {
if (matrix[0][j] == target) {
return true;
} else if (matrix[0][j] > target) {
continue;
} else {
for (int i = 1; i < rows; i++) {
if (matrix[i][j] == target) {
return true;
} else if (i == rows - 1) {
break;
} else {
continue;
}
}
}
}
return false;
}
}