题目描述:在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
实现代码:
public class FindNumberIn2DArray_04 {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
//防止输入的二维数组为空 报数组下标越界异常
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int rows = matrix.length;//得到数组行数
int cols = matrix[0].length;//得到数组列数
int row = rows - 1;//以数组左下角开始 matrix[rows-1][0]
int col = 0;
//当前行>=0 且 当前列 <= 总列数-1
while (row>=0 && col <= cols-1){
//二维数组有序排列,向上递减,向右递增
if (matrix[row][col] > target ){
row--;
}else if (matrix[row][col] < target){
col++;
}else {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[][] matrix= {{1, 4, 7, 11, 15},{2, 5, 8, 12, 19}};
FindNumberIn2DArray_04 find = new FindNumberIn2DArray_04();
Boolean ok = find.findNumberIn2DArray(matrix,3);
System.out.println(ok);
}
}