面試題04.二維數組中的查找
題目描述
在一個 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。
限制:
0 <= n <= 1000
0 <= m <= 1000
題解
1、暴力法:遍歷整個數組,找到目標返回true,找不到返回false;
2、橫豎都是遞增的,那麼我們從最右上角開始,比目標值大就列數減一,比目標值大就行數加一,知道找到爲止,要注意的是,數組爲空的時候要特別判斷一下,代碼如下:(暴力法省略)
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {
return false;
}
int heng = matrix[0].length-1;
int shu = 0;
while(shu<matrix.length&&heng>=0){
if(matrix[shu][heng]<target){
shu++;
}else if(matrix[shu][heng]>target){
heng--;
}else{
return true;
}
}
return false;
}
}