240.Search a 2D Matrix II
现有矩阵 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]
]class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty()) return false;
int row=matrix.size();
int col=matrix[0].size();
if(matrix[row-1][col-1]<target) return false;
int rstart=0,cstart=col-1;
while( rstart<row && cstart >= 0)
{
if(matrix[rstart][cstart] == target) return true;
else if(matrix[rstart][cstart] < target) ++rstart;
else --cstart;
}
return false;
}
};Last updated