leetCode_Trapping Rain Water

题意:给定n个非负数代表每个柱子的高度,宽度均为1。问能在空间里放多少水。

解法:设定previous与next,然后移动next,找到第一个比prevoius高的或者比prevoius低的柱子当中最高的。然后两者较低的乘以宽度-所有柱子的高度之和即为prevoius,next之间的蓄水量。然后让prevoius=next,依次循环。挺虐的,做了小半天才AC。

代码:

int trap(vector<int>& height)
{
    int i=0,j,ans=0,size=height.size(),has=0,tsum=0,r=0,ti,pre,next,tmax;
    if(height.size()==0) return 0;
    while(height[i]==0) i++;
    pre=i;
    next=i+1;

    while(pre<size-1)
    {
        tsum=height[pre];
        tmax=-1;
        while(height[next-1]>height[next]&&next<size)
        {
            tsum=tsum+height[next];
            next++;
        }
        if(next>=size) break;
        while(next<size)
        {
            tsum=tsum+height[next];
            if(height[next]>=height[pre])
            {
                tmax=height[next];
                ti=next;
                break;
            }
            else
            {
                if(tmax<height[next])
                {
                    tmax=height[next];
                    ti=next;
                }
            }
            next++;
        }
        if(height[ti]>=height[pre])ans=ans+min(height[pre],height[ti])*(ti-pre+1)-tsum+abs(height[pre]-height[ti]);
        else for(i=pre;i<=ti;i++) if(height[i]<height[ti]) ans+=height[ti]-height[i];
        pre=ti;
        next=ti+1;

    }

    return ans;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值