題目:
編寫一個高效的算法來判斷 m x n 矩陣中,是否存在一個目标值。該矩陣具有如下特性:
- 每行中的整數從左到右按升序排列。
- 每行的第一個整數大于前一行的最後一個整數。
示例 1:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
輸出: true
示例 2:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
輸出: false
解題思路:
先找行,再找列,注意邊界問題,特别是矩陣沒有元素的時候。
也可以使用二分查找,因為數列按大小順序排列了。
代碼實作:
順序查找:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || matrix[0] == null) return false;
int row = matrix.length - 1;
int col = matrix[0].length - 1;
while (row >= 0 && matrix[row][0] > target) {
row --;
}
row = row < 0 ? 0 : row;
while (col >= 0 && matrix[row][col] > target) {
col --;
}
col = col < 0 ? 0 : col;
return matrix[row][col] == target;
}
}
二分查找:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || matrix[0] == null) return false;
int start = 0;
int end = matrix.length - 1;
int row = 0;
int col = 0;
while (start <= end) {
row = start + (end - start) / 2;
if (matrix[row][0] > target) {
end = row -1;
} else if (matrix[row][0] == target){
return true;
} else {
start = row + 1;
}
}
row = end < 0 ? 0 : end;
end = matrix[0].length - 1;
start = 0;
while (start <= end) {
col = start + (end - start) / 2;
if (matrix[row][col] > target) {
end = col - 1;
} else if (matrix[row][col] == target) {
return true;
} else {
start = col + 1;
}
}
col = end < 0 ? 0 : end;
return matrix[row][col] == target;
}
}