leetcode-240. Search a 2D Matrix II 搜索二维矩阵 II

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.

Example:

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]
]

Given target = 5, return true.

Given target = 20, return false.

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例:

现有矩阵 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]
]

给定 target = 5,返回 true

给定 target = 20,返回 false

思路:从左到右有序,从上到下有序。那就从右上角找,如果右上角元素大于target,那就排除最右边一列,因为右上角元素是最右边一列中最小值。若右上角元素小于target,那就排除最上面一行,因为右上角元素是最上面一行中最大的。若相等则找到了。直到循环到遍历到数组左下角。

扫描二维码关注公众号,回复: 6524202 查看本文章
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])

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/90648074