编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
cpp
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size(); // 行数
int cols = matrix[0].size(); // 列数
int x=0;
int y=cols-1;
// 从右上角开始
while(x<rows && y>=0){
if(matrix[x][y] == target) // 找到,返回
return true;
else if(matrix[x][y] > target) // 当前值比目标值大,则继续往左找
y--;
else if(matrix[x][y] < target) // 当前值比目标值小,则继续往下找
x++;
}
return false;
}
};
时间复杂度O(m+n)