Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Example: Consider the following matrix: Given target = Given target = |
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
示例: 现有矩阵 matrix 如下: 给定 target = 给定 target = |
思路:从左到右有序,从上到下有序。那就从右上角找,如果右上角元素大于target,那就排除最右边一列,因为右上角元素是最右边一列中最小值。若右上角元素小于target,那就排除最上面一行,因为右上角元素是最上面一行中最大的。若相等则找到了。直到循环到遍历到数组左下角。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size() || !matrix[0].size()) return false;
if(target<matrix[0][0] || target>matrix.back().back()) return false;
int r=0,c=matrix[0].size()-1;
while(r<matrix.size() && c>=0)
{
if(matrix[r][c]>target) c--;
else if(matrix[r][c]<target) r++;
else return true;
}
return false;
}
};
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any([target in r for r in matrix])