363. 接雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1
, compute how much water it is able to trap after raining.
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1]
, 返回 6
.
int trapRainWater(vector<int> &heights)
{
//363. 接雨水 write your code hereGiven n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
int n=heights.size();
if(n<3) return 0;
int i=1,pre=0,tmp=0,min=0,sum=0;
vector<int> flag(n,0);//每个位置存放heights[i]对应的水平线为heights[flag[i]]
while(i<n&&heights[i]>=heights[i-1]) {flag[i]=i;i++;}
if(i>1) {min=i-1;flag[i]=min;i++;}//先升;
while(i<n)
{
while(i<n&&heights[i]<=heights[min])
{
flag[i]=min;
i++;
}
if(i<n)
{
flag[i]=i;min=i;
}
while(i<n&&heights[i]>=heights[i-1])//升序
{
flag[i]=i;i++;
}
if(i<n)
{
min=i-1;flag[i]=min;
}
}
int max=n-1; flag[n-1]=n-1;
for(i=n-2;i>min;i--)//先从前向后找,最后从后向前找;
{
if(heights[max]<=heights[i]){max=i;flag[i]=i;}
if(heights[i]<heights[max]){flag[i]=max;}
}
for(i=0;i<n;i++)
{
sum+=heights[flag[i]]-heights[i]>0?heights[flag[i]]-heights[i]:heights[i]-heights[flag[i]];
}
return sum;
}