85. Maximal Rectangle
Hard
443491Add to ListShare
Given a rows x cols
binary matrix
filled with 0
's and 1
's, find the largest rectangle containing only 1
's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [["0"]]
Output: 0
Example 4:
Input: matrix = [["1"]]
Output: 1
Example 5:
Input: matrix = [["0","0"]]
Output: 0
Constraints:
rows == matrix.length
cols == matrix[i].length
0 <= row, cols <= 200
matrix[i][j]
is'0'
or'1'
.
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""
assert Solution().largestRectangleArea([1, 6, 5]) == 10
assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10
解题思路:维护一个递增栈,栈底是当前连续递增序列的最小值的索引下标
当当前元素值小等于等于栈顶元素值,取出栈顶元素计算宽度
如[1, 6, 5]:
根据代码:得[1, 6, 5, 0]
第一步:1,6 下标依次入栈,得[0,1],其中右边为栈顶
第二步:判断5比栈顶元素6小,此时取出栈顶,此时高为6,宽度为1
第三步:5,下标入栈,此时[0,2]
第四步:判断0比栈顶元素5小,此时取出栈顶,此时高为5,宽度为2(因为之前高度6大于现在的高度5,宽度+1)
时间复杂度:O(n),空间复杂度:O(n)
"""
# 取巧,为了最后一个也计算进去
heights.append(0)
stack, area = [], 0
for i in range(len(heights)):
while stack and heights[stack[-1]] >= heights[i]:
h = heights[stack.pop()]
w = i if not stack else i - stack[-1] - 1
area = max(area, h * w)
stack.append(i)
return area
def maximalRectangle(self, matrix: List[List[str]]) -> int:
"""
assert Solution().maximalRectangle([
["0", "1"],
["1", "0"]
]) == 1
assert Solution().maximalRectangle([
["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"]
]) == 6
assert Solution().maximalRectangle([
["0"]
]) == 0
assert Solution().maximalRectangle([
["1"]
]) == 1
解题思路:参考题目84. Largest Rectangle in Histogram,把矩阵每行看成以该行为坐标横轴的坐标系。
使用数组h[i],代表第i列当前的柱状高度为h[i]。如果当前值为0,则之前的高度重置,因为这列在这里出现了断层。
时间复杂度:O(n^2),空间复杂度:O(n),其中n为矩阵维数
"""
if matrix is None or len(matrix) == 0:
return 0
res = 0
h = [0] * len(matrix[0])
for row in range(len(matrix)):
for i in range(len(matrix[row])):
if matrix[row][i] == '1':
h[i] += 1
else:
h[i] = 0
res = max(res, self.largestRectangleArea(list(h)))
return res