85. Maximal Rectangle(题目链接)
Hard
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6
方法1:单调栈
这个题可以看成是[Leetcode] 84. Largest Rectangle in Histogram 的扩展。把每一层当做底,如果某个位置为"0",则更新该位置为0,否则+1
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
rlt = 0
heights = [0] * len(matrix[0])
for row in matrix:
for i in range(len(row)):
heights[i] = heights[i] + 1 if row[i] == '1' else 0
rlt = max(rlt, self.largestRectangleArea(heights))
return rlt
def largestRectangleArea(self, heights: List[int]) -> int:
if not heights:
return 0
rlt = 0
stack = []
heights.append(0)
i = 0
while i < len(heights):
if not stack or heights[i] >= heights[stack[-1]]:
stack.append(i)
i += 1
continue
top = stack.pop()
# 算间距的时候,不能用i-top, 测试 4,2,0,3,2,5,0
rlt = max(rlt, heights[top] * (i if not stack else i - stack[-1] - 1))
return rlt
本文详细解析了LeetCode上的经典题目——最大矩形问题,通过使用单调栈算法,将二维矩阵中寻找包含最多1的最大矩形面积问题转化为一系列一维直方图最大矩形面积问题进行求解。
4万+

被折叠的 条评论
为什么被折叠?



