前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 85. Maximal Rectangle

leetcode: 85. Maximal Rectangle

作者头像
JNingWei
发布2018-09-27 17:02:51
6890
发布2018-09-27 17:02:51
举报
文章被收录于专栏:JNing的专栏JNing的专栏

Problem

# Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
#
# For example, given the following matrix:
#
# 1 0 1 0 0
# 1 0 1 1 1
# 1 1 1 1 1
# 1 0 0 1 0
# Return 6.

Idea

From LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

这里写图片描述
这里写图片描述
如果我们把每一行看成x坐标,那高度就是 从那一行开始往上数的1的个数 。

带入我们的maxAreaInHist方法,在O(n2)时间内就可以求出每一行形成的“柱状图”的最大矩形面积了。
它们之中最大的,就是我们要的答案。

AC

class Solution():
    def maximalRectangle(self, x):
        maxArea = 0
        if not x:
            return 0
        vector = [0]* len(x[0])
        for r in x:
            for i, c in enumerate(r):
                if c == '0':
                    vector[i]=0
                else:
                    vector[i]+=1
            maxArea = max(maxArea, self.largestRectangleArea(vector[:]))
        return maxArea

    def largestRectangleArea(self, xs):
        xs.insert(0,0)
        xs.append(0)
        stack, maxArea = [], 0
        for i, x in enumerate(xs):
            if not stack or xs[stack[-1]]<=x:
                stack.append(i)
            else:
                while stack and xs[stack[-1]]>x:
                    maxArea = max(maxArea, xs[stack[-1]]*(i-stack[-2]-1))
                    stack.pop()
                stack.append(i)
        return maxArea


if __name__ == "__main__":
    matrix = ["01101", "11010", "01110", "11110", "11111", "00000"]
    assert Solution().maximalRectangle(matrix) == 9
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
    • Idea
    • AC
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档