提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、84柱状图中最大的矩形
做完接雨水后,这题确实不难了
指针法(超时后根据没通过的样例过滤):
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0;
int n = heights.size();
for (int i = 0; i < n; i ++) {
if (heights[i] == 0 || heights[i] * n <= res || (i > 0 && heights[i] == heights[i-1])) {
continue;
}
int maxLeft = i;
int maxRight = i;
while (maxLeft > 0 && heights[maxLeft -1] >= heights[i]) {
maxLeft --;
}
while (maxRight < n - 1 && heights[maxRight + 1] >= heights[i]) {
maxRight ++;
}
int tmp = heights[i] * (maxRight - maxLeft + 1);
res = max(res, tmp);
}
return res;
}
};
单调栈法:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), 0);
heights.insert(heights.end(), 0);
int n = heights.size();
int res = 0;
stack<int> st;
st.push(0);
for (int i = 1; i < n; i ++) {
while (!st.empty() && heights[i] < heights[st.top()]) {
int h = heights[st.top()];
st.pop();
if (!st.empty()) {
int w = i - st.top() - 1;
res = max(res, h * w);
}
}
st.push(i);
}
return res;
}
};
总结
代码随想录一刷结束!感觉真的学到了不少东西,之前虽然也做了四五百道题,但也没有这么系统刷过题。本次最大的收获是从代码随想录入门c++,希望一切的努力都能在日后有所收获。