File tree Expand file tree Collapse file tree 1 file changed +24
-2
lines changed Expand file tree Collapse file tree 1 file changed +24
-2
lines changed Original file line number Diff line number Diff line change
1
+ 首先 ,要想找到第 i 位置最大面积是什么 ?
2
+ 是以 i 为中心 ,向左找第一个小于 heights [i ] 的位置 left_i ;向右找第一个小于于 heights [i ] 的位置 right_i ,
3
+ 即最大面积为 heights [i ] * (right_i - left_i - 1 )
4
+ 所以 ,我们的问题就变成如何找right_i 和 left_i ?
5
+
6
+ # 暴力解法,会超时
7
+ class Solution :
8
+ def largestRectangleArea (self , heights : List [int ]) -> int :
9
+ res = 0
10
+ n = len (heights )
11
+ for i in range (n ):
12
+ left_i = i
13
+ right_i = i
14
+ while left_i >= 0 and heights [left_i ] >= heights [i ]:
15
+ left_i -= 1
16
+ while right_i < n and heights [right_i ] >= heights [i ]:
17
+ right_i += 1
18
+ res = max (res , (right_i - left_i - 1 ) * heights [i ])
19
+ return res
20
+
21
+ # 单调栈
1
22
class Solution :
2
23
def largestRectangleArea (self , heights : List [int ]) -> int :
3
- heights = [0 ] + heights + [0 ]
24
+ heights = [0 ] + heights + [0 ] #如果遍历之后,栈不为空,那么还需要一步:即弹出栈中所有元素,分别计算最大面积。然而当加了两个0以后,在结束后,栈一定为空!
25
+ # 因为0入栈的时候,会把前面所有的数全部弹出,如果0最后一个入栈,所有的数都会弹出;头部加0便于处理当栈里只有一个有效元素要弹出的时候计算面积
4
26
res = 0
5
27
stack = []
6
28
for i in range (len (heights )):
@@ -9,4 +31,4 @@ def largestRectangleArea(self, heights: List[int]) -> int:
9
31
res = max (res , (i - stack [- 1 ] - 1 ) * heights [top ])
10
32
11
33
stack .append (i )
12
- return res
34
+ return res
You can’t perform that action at this time.
0 commit comments