mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 21:50:49 +08:00
Update 0084.柱状图中最大的矩形.md 动态规划和单调栈 Python3 版本
This commit is contained in:
@ -191,4 +191,57 @@ public:
|
||||
|
||||
这里我依然建议大家按部就班把版本一写出来,把情况一二三分析清楚,然后在精简代码到版本二。 直接看版本二容易忽略细节!
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
Java:
|
||||
|
||||
Python:
|
||||
|
||||
动态规划
|
||||
```python3
|
||||
class Solution:
|
||||
def largestRectangleArea(self, heights: List[int]) -> int:
|
||||
result = 0
|
||||
minleftindex, minrightindex = [0]*len(heights), [0]*len(heights)
|
||||
|
||||
minleftindex[0]=-1
|
||||
for i in range(1,len(heights)):
|
||||
t = i-1
|
||||
while t>=0 and heights[t]>=heights[i]: t=minleftindex[t]
|
||||
minleftindex[i]=t
|
||||
|
||||
minrightindex[-1]=len(heights)
|
||||
for i in range(len(heights)-2,-1,-1):
|
||||
t=i+1
|
||||
while t<len(heights) and heights[t]>=heights[i]: t=minrightindex[t]
|
||||
minrightindex[i]=t
|
||||
|
||||
for i in range(0,len(heights)):
|
||||
left = minleftindex[i]
|
||||
right = minrightindex[i]
|
||||
summ = (right-left-1)*heights[i]
|
||||
result = max(result,summ)
|
||||
return result
|
||||
```
|
||||
单调栈 版本二
|
||||
```python3
|
||||
class Solution:
|
||||
def largestRectangleArea(self, heights: List[int]) -> int:
|
||||
heights.insert(0,0) # 数组头部加入元素0
|
||||
heights.append(0) # 数组尾部加入元素0
|
||||
st = [0]
|
||||
result = 0
|
||||
for i in range(1,len(heights)):
|
||||
while st!=[] and heights[i]<heights[st[-1]]:
|
||||
midh = heights[st[-1]]
|
||||
st.pop()
|
||||
if st!=[]:
|
||||
minrightindex = i
|
||||
minleftindex = st[-1]
|
||||
summ = (minrightindex-minleftindex-1)*midh
|
||||
result = max(summ,result)
|
||||
st.append(i)
|
||||
return result
|
||||
```
|
||||
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码.jpg width=450> </img></div>
|
||||
|
Reference in New Issue
Block a user