这一题也是没想到方法,按照网上的做法写了一遍,思想是:
”
网上看到一种借助栈的做法,代码很漂亮,但是解释都非常模糊,我看懂之后,决定仔细描述思路如下:
1、如果已知height数组是升序的,应该怎么做?
比如1,2,5,7,8
那么就是(15) vs. (24) vs. (53) vs. (72) vs. (81)
也就是max(height[i](size-i))
2、使用栈的目的就是构造这样的升序序列,按照以上方法求解。
但是height本身不一定是升序的,应该怎样构建栈?
比如2,1,5,6,2,3
(1)2进栈。s={2}, result = 0
(2)1比2小,不满足升序条件,因此将2弹出,并记录当前结果为21=2。
将2替换为1重新进栈。s={1,1}, result = 2
(3)5比1大,满足升序条件,进栈。s={1,1,5},result = 2
(4)6比5大,满足升序条件,进栈。s={1,1,5,6},result = 2
(5)2比6小,不满足升序条件,因此将6弹出,并记录当前结果为61=6。s={1,1,5},result = 6
2比5小,不满足升序条件,因此将5弹出,并记录当前结果为52=10(因为已经弹出的5,6是升序的)。s={1,1},result = 10
2比1大,将弹出的5,6替换为2重新进栈。s={1,1,2,2,2},result = 10
(6)3比2大,满足升序条件,进栈。s={1,1,2,2,2,3},result = 10
栈构建完成,满足升序条件,因此按照升序处理办法得到上述的max(height[i](size-i))=max{31, 22, 23, 24, 15, 16}=8<10
综上所述,result=10
“
以下是我写的代码
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
res = 0
stack = []
for i in range(len(heights)):
if len(stack) == 0 or heights[i] >= stack[-1]:
stack.append(heights[i])
else:
count = 0
while len(stack) != 0 and heights[i] < stack[-1]:
count += 1
res = max(res, count * stack[-1])
stack.pop()
while count >= 0:
stack.append(heights[i])
count -= 1
count = 1
while count <= len(stack):
res = max(res, count * stack[len(stack) - count])
count += 1
return res