zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):085-Maximal Rectangle

    题目来源:

      https://leetcode.com/problems/maximal-rectangle/


    题意分析:

      给定一个二维的二进制矩阵,也就是只包括0 和 1的,找出只包括1的最大的矩阵的面积。


    题目思路:

      这道题目可以用84题的解决方法去解决。如果选定了一行为起点,这一行向上或者向下从这行开始连续1的个数是bar的高度,那么就可以求出以这一行起得到的最大的矩阵面积。遍历所有的行,得到最大的结果为这题的最后结果。


    代码(python):

      

    class Solution(object):
        def maximalRectangle(self, matrix):
            """
            :type matrix: List[List[str]]
            :rtype: int
            """
            m = len(matrix)
            if m == 0:
                return 0
            n = len(matrix[0])
            def solve(s):
                mans = 0
                ans,ansindex,i = [],[],0
                while i < len(s):
                    if len(ans) == 0 or s[i] >ans[-1]:
                        ans.append(s[i]);ansindex.append(i)
                    elif s[i] < ans[-1]:
                        lastindex = 0
                        while len(ans) > 0 and ans[-1] > s[i]:
                            lastindex = ansindex.pop()
                            mans = max(mans,ans.pop() * (i - lastindex))
                        ans.append(s[i]);ansindex.append(lastindex)
                    i += 1
                while len(ans) != 0:
                    mans = max(mans,ans.pop() * (len(s) - ansindex.pop()))
                return mans
            s = [0 for i in range(n)]
            ans = 0
            for i in range(m):
                for j in range(n):
                    if matrix[i][j] == '1':
                        s[j] += 1
                    else:
                        s[j] = 0
                ans = max(ans,solve(s))
            return ans
    View Code
  • 相关阅读:
    组件开发的博客信息
    读书片断之 开发自定义HTTP模块
    .NET2.0抓取网页全部链接
    数据分页处理方法汇总(例子)
    GridView添加统计(合计)行
    JS中$含义及用法
    Hashtable, ArrayList, List, Dictionary学习
    C#自定义消息映射!
    winform等待窗口
    DataView的RowFilter特殊字符的处理
  • 原文地址:https://www.cnblogs.com/chruny/p/5213640.html
Copyright © 2011-2022 走看看