• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

[LeetCode] Search a 2D Matrix II

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);
        }
    }
};


posted on 2017-05-04 16:56  cynchanpin  阅读(136)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3