Skip to content

Commit 453aa7f

Browse files
lijiafan60yanglbme
andauthored
feat: add cpp solution to lcof2 problem: No.040 (#832)
No.040.Maximal Rectangle Co-authored-by: Yang Libin <contact@yanglibin.info>
1 parent 48e2d77 commit 453aa7f

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

lcof2/剑指 Offer II 040. 矩阵中最大的矩形/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,13 @@
6767

6868
<!-- 这里可写通用的实现逻辑 -->
6969

70+
**方法一:单调栈**
71+
72+
- 首先在柱状图中求最大矩形面积可以通过单调栈,维护每一列的左边第一个比它小的位置 $L$,和右边第一个比它小的位置 $R$,就能得到以这一列为高的最大矩形面积为 $(R-L-1)*h$。
73+
- 考虑每一行作为底边的柱状图中,能够得到的最大的矩形面积。再对每一行的最大面积取 $max$ 就是最终的答案。
74+
- 柱状图中每一列的高可以通过类似前缀和的方式去维护。
75+
- 假设矩阵大小为 $n*m$,那么时间复杂为 $O(nm)$,空间复杂度为 $O(m)$。
76+
7077
<!-- tabs:start -->
7178

7279
### **Python3**
@@ -85,6 +92,44 @@
8592

8693
```
8794

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+
88133
### **...**
89134
90135
```
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
};

0 commit comments

Comments
 (0)