劍指offer之二維陣列中的查詢(Java實現)
阿新 • • 發佈:2018-12-22
2. 二維陣列中的查詢
題目描述
在一個二維陣列中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。
Consider the following 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] ] Given target = 5, return true. Given target = 20, return false.
解題思路
從右上角開始查詢。矩陣中的一個數,它左邊的數都比它小,下邊的數都比它大。因此,從右上角開始查詢,就可以根據 target 和當前元素的大小關係來縮小查詢區間。
複雜度:O(M + N) + O(1)
public boolean Find(int target, int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return false;
int rows = matrix.length, cols = matrix[0].length;
int r = 0, c = cols - 1; // 從右上角開始
while (r <= rows - 1 && c >= 0) {
if (target == matrix[r][c])
return true;
else if (target > matrix[r][c])
r++;
else
c--;
}
return false;
}