File tree 2 files changed +49
-0
lines changed
lcof2/剑指 Offer II 039. 直方图最大矩形面积
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 63
63
64
64
```
65
65
66
+ ### ** C++**
67
+
68
+ 我们遍历每个柱体,若当前的柱体高度大于等于栈顶柱体的高度,就直接将当前柱体入栈,否则若当前的柱体高度小于栈顶柱体的高度,说明当前栈顶柱体找到了右边的第一个小于自身的柱体,那么就可以将栈顶柱体出栈来计算以其为高的矩形的面积了。
69
+
70
+ ``` cpp
71
+ class Solution {
72
+ public:
73
+ int largestRectangleArea(vector<int >& heights) {
74
+ int maxarea = 0;
75
+ stack<int > s;
76
+ heights.insert(heights.begin(), 0);
77
+ heights.push_back(0);
78
+
79
+ for (int i = 0; i < heights.size(); i++) {
80
+ while (!s.empty() && heights[i] < heights[s.top()]) {
81
+ int h = heights[s.top()];
82
+ s.pop();
83
+ maxarea = max(maxarea, h * (i - s.top() - 1));
84
+ }
85
+
86
+ s.push(i);
87
+ }
88
+
89
+ return maxarea;
90
+ }
91
+ };
92
+ ```
93
+
66
94
### ** ...**
67
95
68
96
```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int largestRectangleArea (vector<int >& heights) {
4
+ int maxarea = 0 ;
5
+ stack<int > s;
6
+ heights.insert (heights.begin (), 0 );
7
+ heights.push_back (0 );
8
+
9
+ for (int i = 0 ; i < heights.size (); i++) {
10
+ while (!s.empty () && heights[i] < heights[s.top ()]) {
11
+ int h = heights[s.top ()];
12
+ s.pop ();
13
+ maxarea = max (maxarea, h * (i - s.top () - 1 ));
14
+ }
15
+
16
+ s.push (i);
17
+ }
18
+
19
+ return maxarea;
20
+ }
21
+ };
You can’t perform that action at this time.
0 commit comments