题目:
编写一个高效的算法来搜索 m xn 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
示例 1:

输入: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
示例 2:

输入: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 = 20
输出:false
右上角的特点:
1, 4, 7, 11, 15\] ← 从这里开始 \[2, 5, 8, 12, 19
3, 6, 9, 16, 22
当前位置的左边都比它小 ←
当前位置的下边都比它大 ↓
所以:
-
如果 target < 当前值 → 向左移动(排除当前列)
-
如果 target > 当前值 → 向下移动(排除当前行)
-
如果 target = 当前值 → 找到
左上角/右下角为什么不行?
左上角: 右边和下边都可能有更大的值,无法确定方向
右下角: 左边和上边都可能有更小的值,无法确定方向
题解(右上角版本)
java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) return false;
int row = 0; // 从第一行开始
int col = matrix[0].length - 1; // 从最后一列开始(右上角)
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--; // 当前值太大,向左
} else {
row++; // 当前值太小,向下
}
}
return false;
}
}
题解(左下角版本)
java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) return false;
int row = matrix.length - 1; // 从最后一行开始
int col = 0; // 从第一列开始(左下角)
while (row >= 0 && col < matrix[0].length) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
row--; // 当前值太大,向上
} else {
col++; // 当前值太小,向右
}
}
return false;
}
}
解法(右上角搜索)
- 时间复杂度: O(m + n) --- 最多走 m+n 步
- 空间复杂度: O(1)