题目:
编写一个高效的算法来判断 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;
}
}