LeetCode刷题实战85: 最大矩形
共 3021字,需浏览 7分钟
·
2020-11-07 02:18
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 最大矩形,我们先来看题面:
https://leetcode-cn.com/problems/maximal-rectangle/
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.
题意
解题
题解
暴力
分析问题
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
# 求出行数n和列数m
n = len(matrix)
if n == 0:
return 0
m = len(matrix[0])
# 存储每一层的高度
height = [0 for _ in range(m+1)]
res = 0
# 遍历以哪一层作为底层
for i in range(n):
sk = [-1]
for j in range(m+1):
# 计算j位置的高度,如果遇到0则置为0,否则递增
h = 0 if j == m or matrix[i][j] == '0' else height[j] + 1
height[j] = h
# 单调栈维护长度
while len(sk) > 1 and h < height[sk[-1]]:
res = max(res, (j-sk[-2]-1) * height[sk[-1]])
sk.pop()
sk.append(j)
return res
总结
上期推文: