面试题04. 二维数组中的查找
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
时间复杂度: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 rows = matrix.length - 1;
int cols = matrix[0].length - 1;
int temp_rows = 0;
int temp_cols = cols;
while(temp_rows <= rows && temp_cols >= 0){
if(matrix[temp_rows][temp_cols] == target){
return true;
}else if(matrix[temp_rows][temp_cols] > target){
temp_cols--;
}else{
temp_rows++;
}
}
return false;
}
}