zoukankan      html  css  js  c++  java
  • [leetcode]Maximal Rectangle @ Python

    原题地址:https://oj.leetcode.com/problems/maximal-rectangle/

    题意:Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

    解题思路:找出矩阵中最大的矩形,矩形中只包含1。这道题需要利用上一道题(Largest Rectangle in Histogram)的结论。比如对于以下矩阵。

            0 0 0 0

            0 0 1 0

            0 1 1 0

            1 0 1 1

         对于这个矩阵,对于每一行,我们按照上一道题的算法求解一遍,最后得出的就是最大的矩阵。

    代码:

    class Solution:
        # @param matrix, a list of lists of 1 length string
        # @return an integer
        def largestRectangleArea(self, height):
            stack=[]; i=0; area=0
            while i<len(height):
                if stack==[] or height[i]>height[stack[len(stack)-1]]:
                    stack.append(i)
                else:
                    curr=stack.pop()
                    width=i if stack==[] else i-stack[len(stack)-1]-1
                    area=max(area,width*height[curr])
                    i-=1
                i+=1
            while stack!=[]:
                curr=stack.pop()
                width=i if stack==[] else len(height)-stack[len(stack)-1]-1
                area=max(area,width*height[curr])
            return area
            
        def maximalRectangle(self, matrix):
            if matrix==[]: return 0
            a=[0 for i in range(len(matrix[0]))]; maxArea=0
            for i in range(len(matrix)):
                for j in range(len(matrix[i])):
                    a[j]=a[j]+1 if matrix[i][j]=='1' else 0
                
                maxArea=max(maxArea, self.largestRectangleArea(a))
            
            return maxArea
            
  • 相关阅读:
    模块和包
    网络基础之网络协议
    计算机硬件知识
    面试题集锦(一)
    二分查找法
    ORM多表操作示例
    Django之URL(路由系统)用法
    用Nginx实现微信小程序本地SSL请求
    [PHP7.0-PHP7.2]的新特性和新变更
    利用Node的chokidar 监听文件改变的文件。
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3784252.html
Copyright © 2011-2022 走看看