单调栈day54|42. 接雨水(高频面试题)、84. 柱状图中最大的矩形、两道题思维导图的汇总与对比
单调栈day54|42. 接雨水(高频面试题)、84. 柱状图中最大的矩形、两道题思维导图的汇总与对比
- 42. 接雨水
- 84. 柱状图中最大的矩形
- 两道题思维导图的汇总与对比
42. 接雨水
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 1:
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
提示:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
class Solution {
public:int trap(vector<int>& height) {int sum=0;stack<int> st;st.push(0);for(int i=1;i<height.size();i++){if(height[i]<=height[st.top()])st.push(i);else{while(!st.empty()&&height[i]>height[st.top()]){int mid=height[st.top()];st.pop();if(!st.empty()){int h=min(height[st.top()],height[i])-mid;int w=i-st.top()-1;sum+=h*w;}}st.push(i);}}return sum;}
};
具体的分析过程如下面的思维导图所示:
84. 柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
提示:
1 <= heights.length <=105
0 <= heights[i] <= 104
class Solution {
public:int largestRectangleArea(vector<int>& heights) {stack<int> st;int result=0;heights.insert(heights.begin(),0);heights.push_back(0);st.push(0);for(int i=0;i<heights.size();i++){if(heights[i]>=heights[st.top()])st.push(i);else{while(!st.empty()&&heights[i]<heights[st.top()]){int mid=st.top();st.pop();if(!st.empty()){int h=heights[mid];int w=i-st.top()-1;result=max(result,h*w);}}st.push(i);}}return result;}
};
具体的分析过程如下面的思维导图所示: