42. 接雨水
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
法一
找出每根柱子左右的最高点,取两边最高柱子最小的高度,与中间柱子高度相减就是凹槽的高度
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> left(n),right(n);
for(int i=1;i<n;i++) // 左边最高的点
left[i] = max(left[i-1],height[i-1]);
for(int j=n-2;j>=0;j--) // 右边最高的点
{
right[j] = max(right[j+1],height[j+1]);
}
int w = 0;
for(int i=0;i<n;i++)
{
int level = min(left[i],right[i]);
w+=max(0,level-height[i]);
}
return w;
}
};
单调栈法
维护一个单调递减栈,当当前元素小于栈顶元素时,进栈,当大于栈顶元素时,说明可以构成一个凹槽,栈顶元素出栈,并判断栈顶元素两边柱子的最小高度,取最小高度作为凹槽的高度。直到碰到栈顶元素大于当前元素时再次进栈。
思路还是要找到栈顶柱子两边的最小柱子的高度,然后乘上柱子之间的宽度就是凹槽盛水的容积。
class Solution {
public:
int trap(vector<int>& height) {
int ans = 0;
stack<int> st;
for(int i=0;i<height.size();i++)
{
while(!st.empty()&&height[st.top()]<height[i])
{
int t = st.top(); //取出栈顶的柱子
st.pop(); //抛出栈顶元素,并确定柱子两边最小高度的柱子
if(st.empty()) break; //如果栈空了,说明不能构成凹槽,比如开始进去的柱子是0,1,1比0大,所以抛出0,再次比较时,栈空了,不能构成一个凹槽
if(height[t] == height[st.top()]) continue;
int width = i-st.top()-1; // 求出凹槽的宽度
int h = min(height[st.top()],height[i]);
ans+=(h-height[t])*width;
}
st.push(i);
}
return ans;
}
};
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<stack>
using namespace std;
int n;
int nums[20005];
stack<int> st;
int ans;
int main()
{
// freopen("test.txt","r",stdin);
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",nums+i);
}
for(int i=0;i<n;i++)
{
int width = 0;
while(!st.empty()&&nums[st.top()]<nums[i])
{
int t = st.top();
st.pop();
if(st.empty()) break;
if(nums[t] == nums[st.top()])
continue;
width = i-st.top()-1;
int h = min(nums[i],nums[st.top()]);
ans += width*(h - nums[t]);
}
st.push(i);
}
printf("%d\n",ans);
return 0;
}