剑指 Offer 04. 二维数组中的查找
分析
存在一个m*n数组,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[ [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]]
如果把数组的右上元素作为根节点,其左边子节点必小于它,右边子节点必大于它,因此,可以近似看作一颗二叉排序树,从其右上元素开始遍历,由此,算法的时间复杂度为O(max(m,n))。
代码
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length==0 || (matrix.length == 1 && matrix[0].length==0) || matrix[0][0]>target || matrix[matrix.length-1][matrix[0].length-1]<target) return false;
int i = 0;
int j = matrix[0].length-1;
while (i < matrix.length && j >= 0){
if (matrix[i][j] < target){
j++;
}else if(matrix[i][j] > target){
i--;
}else {
return true;
}
}
return false;
}
注意点:
需要先行判断数组为空的情况,,java如何判断一个二维数组为空。
- 应该分为三个情况:
- 第一,判断数组首地址是否为空:matrix == null
- 第二,判断是否为{}这种情况:matrix.length == 0
- 第三,判断是否为{{}}这种情况:matrix.length == 1 && matrix[0].length == 0