题目
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.
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] ]
Example 1:
Input: matrix, target = 5
Output: true
Example 2:
Input: matrix, target = 20 Output: false
思路:从矩阵右上角开始找,若matrix[i][j]<target,因为矩阵从左至右递增,则第i行的数都会小于target,于是i++;若matrix[i][j]>target,因为矩阵从上至下递增,则第j列的数都会大于target,于是j--。
代码:
class Solution {
public:
//240. Search a 2D Matrix II
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0) return false;
int i = 0, j = matrix[0].size() - 1;
while(i>=0 && j>=0 && i<matrix.size() && j<matrix[0].size()){
if(matrix[i][j] == target) return true;
else if(matrix[i][j] < target) i++;
else j--;
}
return false;
}
};