码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Search a 2D Matrix II

时间:2015-07-24 14:23:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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<vector<int>>& 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<vector<int>>& 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]<target){
            return  searchMatrixHelper(matrix, startM, endM, middleN + 1, endN, target) ||
                    searchMatrixHelper(matrix, middleM + 1, endM, startN, middleN, target);
        }else{
            return  searchMatrixHelper(matrix, startM, middleM - 1, startN, endN, target) ||
                    searchMatrixHelper(matrix, middleM, endM, startN, middleN - 1, target);
        }
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Search a 2D Matrix II

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47039599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!