面试题 10.09. 排序矩阵查找
给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。
示例:
现有矩阵 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) {
// int cur = matrix[0][col];
if(matrix.size() == 0){
return false;
}
int row = 0, col = matrix[0].size() - 1;
while(row < matrix.size() && col >= 0){
if(target == matrix[row][col]){
return true;
}else if(target > matrix[row][col]){
++row;
}else{
--col;
}
}
return false;
}
};