ITPub博客

首页 > > > [LeetCode] Search a 2D Matrix II

[LeetCode] Search a 2D Matrix II

作者:Ruiyuan Li 时间:2015-07-24 00:00:00 0 删除 编辑

Search a 2D Matrix 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.

解题思路:

咋一看,还不知如何下手,因为这样不能像此前Search a 2D Matrix那样,将二维坐标转化成一维坐标。其实可以从二维的角度来将矩阵划分。


矩阵中心为9,其中左上角的所有元素均小于等于9,右下角的元素均大于9。因此,我们可以每次对比矩阵中心元素,然后排出左上角或右下角区域即可。下面是代码:

class Solution {
public:
    bool searchMatrix(vector>& matrix, int target) {
        int m = matrix.size();
        if(m<=0){
            return false;
        }
        int n = matrix[0].size();
        if(n<=0){
            return false;
        }
        return searchMatrixHelper(matrix, 0, m-1, 0, n-1, target);
    }
    
    bool searchMatrixHelper(vector>& matrix, int startM, int endM, int startN, int endN, int target){
        if(startM > endM || startN > endN){
            return false;
        }
        int middleM = (startM + endM) / 2;
        int middleN = (startN + endN) / 2;
        if(matrix[middleM][middleN]==target){
            return true;
        }else if(matrix[middleM][middleN]


转载请注明: » [LeetCode] Search a 2D Matrix II
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825