剑指offer 04 二维数组中的查找
二维数组中的查找
思路:
[
[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]
]
这个题可以直接用暴力法找出目标值。
但从上面的示例可以看出,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
如果我们从最左下角找,也就是上述示例的18。
如果目标值大于该值,我们就可以直接排除一行;
如果目标值小于该值,我们就可以直接排除一列;
直到找到目标值返回true,或者超过了寻找范围,返回false。
代码:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if ((matrix.length == 0) || (matrix[0].length) == 0)
return false;
int rows = matrix.length;
int columns = matrix[0].length;
int row = rows - 1;
int column = 0;
while ((row >= 0) && (column < columns))
if (matrix[row][column] == target)
return true;
else if (matrix[row][column] > target) {
row--;
}
else {
column++;
}
return false;
}
}