[LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.

For 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.

74. Search a 2D Matrix 的变形,这题的矩阵特点是:每一行是按从左到右升序排列;每一列从上到下按升序排列。

解法:有特点的数是左下角和右上角的数。比如左下角的18开始,上面的数比它小,右边的数比它大,和目标数相比较,如果目标数大,就往右搜,如果目标数小,就往上搜。这样就可以判断目标数是否存在。或者从右上角15开始,左面的数比它小,下面的数比它大。

Python:

class Solution:
    def searchMatrix(self, matrix, target):
        m = len(matrix)
        if m == 0:
            return False
        
        n = len(matrix[0])
        if n == 0:
            return False
            
        i, j = 0, n - 1
        while i < m and j >= 0:
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                j -= 1
            else:
                i += 1
                
        return False

C++:

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        if (matrix.empty() || matrix[0].empty()) return false;
        if (target < matrix[0][0] || target > matrix.back().back()) return false;
        int x = matrix.size() - 1, y = 0;
        while (true) {
            if (matrix[x][y] > target) --x;
            else if (matrix[x][y] < target) ++y;
            else return true;
            if (x < 0 || y >= matrix[0].size()) break;
        }
        return false;
    }
};

  

类似题目:

[LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

 

All LeetCode Questions List 题目汇总

 

以上是关于[LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode240:Search a 2D Matrix II

LeetCode240. Search a 2D Matrix II

LeetCode240. Search a 2D Matrix II

leetcode No240. Search a 2D Matrix II

[二分搜索] leetcode 240 Search a 2D Matrix II

leetcode 240-Search a 2D Matrix II(medium)