Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
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比该元素小,则说明target不在这一列,如果target比该元素大,则说明target不在这一行,如果相等,则直接返回true。每一次的比较都能删除一行或者一列的查找,到最后如果全部行和列都被删除了,则说明我们在矩阵中找不到target,最后则返回false。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0) return false;
if (matrix[0].size() == 0) return false;
int i = 0;
int j = matrix[0].size() - 1;
while (i < matrix.size() && j >=0) {
if (target == matrix[i][j]) return true;
if (target < matrix[i][j]) {
j--;
}
if (target > matrix[i][j]) {
i++;
}
}
return false;
}
};