zoukankan      html  css  js  c++  java
  • 【LeetCode】240. 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.

    递归,每层排除中心元素左上角或者右下角的1/4

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.empty() || matrix[0].empty())
                return false;
            int m = matrix.size();
            int n = matrix[0].size();
            return Helper(matrix, 0, m-1, 0, n-1, target);
        }
        bool Helper(vector<vector<int>>& matrix, int rlow, int rhigh, int clow, int chigh, int target)
        {
            if(rlow > rhigh || clow > chigh)
                return false;
            if(rlow == rhigh && clow == chigh)
                return matrix[rlow][clow] == target;
            int rmid = (rlow + rhigh) / 2;
            int cmid = (clow + chigh) / 2;
            int val = matrix[rmid][cmid];
            if(val == target)
                return true;
            else if(val > target)
                return Helper(matrix, rlow, rmid-1, clow, chigh, target)
                    || Helper(matrix, rmid, rhigh, clow, cmid-1, target);
            else
                return Helper(matrix, rmid+1, rhigh, clow, chigh, target)
                    || Helper(matrix, rlow, rmid, cmid+1, chigh, target);
        }
    };

  • 相关阅读:
    Django的路由层详情
    如何创建一个django工程与和mysql打通
    初识Django
    初识爬虫
    MongoDB 全部笔记
    爬取视频案例
    课程接口调试
    vue的初识与简单使用---前后端分离通过接口调取数据
    requirements.txt 的使用与创建
    数字与字符串类型
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4676644.html
Copyright © 2011-2022 走看看