File tree Expand file tree Collapse file tree 2 files changed +78
-0
lines changed
lcof2/剑指 Offer II 040. 矩阵中最大的矩形 Expand file tree Collapse file tree 2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change 67
67
68
68
<!-- 这里可写通用的实现逻辑 -->
69
69
70
+ ** 方法一:单调栈**
71
+
72
+ - 首先在柱状图中求最大矩形面积可以通过单调栈,维护每一列的左边第一个比它小的位置 $L$,和右边第一个比它小的位置 $R$,就能得到以这一列为高的最大矩形面积为 $(R-L-1)* h$。
73
+ - 考虑每一行作为底边的柱状图中,能够得到的最大的矩形面积。再对每一行的最大面积取 $max$ 就是最终的答案。
74
+ - 柱状图中每一列的高可以通过类似前缀和的方式去维护。
75
+ - 假设矩阵大小为 $n* m$,那么时间复杂为 $O(nm)$,空间复杂度为 $O(m)$。
76
+
70
77
<!-- tabs:start -->
71
78
72
79
### ** Python3**
85
92
86
93
```
87
94
95
+ ### ** C++**
96
+
97
+ ``` cpp
98
+ class Solution {
99
+ public:
100
+ int h[ 210] ;
101
+ int l[ 210] , r[ 210] ;
102
+ int maximalRectangle(vector<string >& matrix) {
103
+ int n = matrix.size();
104
+ if (n == 0) return 0;
105
+ int m = matrix[ 0] .size();
106
+ int ans = 0;
107
+ stack<int > st;
108
+ for (int i = 0; i < n; i++)
109
+ {
110
+ for (int j = 0; j < m; j++)
111
+ {
112
+ h[ j] = (matrix[ i] [ j ] == '1' ? h[ j] + 1 : 0);
113
+ while (st.size() && h[ j] <= h[ st.top()] )
114
+ {
115
+ ans = max(ans, (j - l[ st.top()] - 1) * h[ st.top()] );
116
+ st.pop();
117
+ }
118
+ if (st.size()) l[ j] = st.top();
119
+ else l[ j] = -1;
120
+ st.push(j);
121
+ }
122
+ while (st.size())
123
+ {
124
+ ans = max(ans, (m - 1 - l[ st.top()] ) * h[ st.top()] );
125
+ st.pop();
126
+ }
127
+ }
128
+ return ans;
129
+ }
130
+ };
131
+ ```
132
+
88
133
### **...**
89
134
90
135
```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int h[210 ];
4
+ int l[210 ], r[210 ];
5
+ int maximalRectangle (vector<string>& matrix) {
6
+ int n = matrix.size ();
7
+ if (n == 0 ) return 0 ;
8
+ int m = matrix[0 ].size ();
9
+ int ans = 0 ;
10
+ stack<int > st;
11
+ for (int i = 0 ; i < n; i++)
12
+ {
13
+ for (int j = 0 ; j < m; j++)
14
+ {
15
+ h[j] = (matrix[i][j] == ' 1' ? h[j] + 1 : 0 );
16
+ while (st.size () && h[j] <= h[st.top ()])
17
+ {
18
+ ans = max (ans, (j - l[st.top ()] - 1 ) * h[st.top ()]);
19
+ st.pop ();
20
+ }
21
+ if (st.size ()) l[j] = st.top ();
22
+ else l[j] = -1 ;
23
+ st.push (j);
24
+ }
25
+ while (st.size ())
26
+ {
27
+ ans = max (ans, (m - 1 - l[st.top ()]) * h[st.top ()]);
28
+ st.pop ();
29
+ }
30
+ }
31
+ return ans;
32
+ }
33
+ };
You can’t perform that action at this time.
0 commit comments