363. 接雨水

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.

Trapping Rain Water

样例

如上图所示,海拔分别为 [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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值