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] ]题意:给定一个矩阵,每个点的值小于其下边和右边的值,查找矩阵中是否存在值target。
思路:由于每个点都小于其下边的右边的值,所以从左下的那个点看,则上边分支的点都小于它,右边分支的点都大于它,类似于二叉搜索树,这样的话从该点出发,若遇大则右移,遇小则上移,同理其他点也做同样的处理,直到找到或者越界(找不到)。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0)
return false;
int n = matrix[0].size();
int i = m - 1;
int j = 0;
while (i >= 0 && j < n){
if (matrix[i][j] == target)
return true;
else if (matrix[i][j] > target)
i--;
else
j++;
}
return false;
}
};