42. Trapping Rain Water

public class Solution {
    public int trap(int[] height) {

        int first = 0;
        int last = height.length-1;
        for(int i=0;i<height.length;i++){
            if(height[i]!=0){first=i;break;}
        }//找到开始的地方
        for(int i=height.length-1;i>=0;i--){
            if(height[i]!=0){last = i;break;}
        }//找到最后的地方,防止最后是0
        int count = 0;//水量

        while(first<last){

            if(height[first]<height[last]){

                for(int i=first+1;i<last;i++){
                    if(height[i]<height[first]){//第一种情况,起点高度小于终点高度
                        count+=height[first] - height[i];
                        height[i] = height[first];
                    }//从结尾到起点,凡是比起点小的,都变成起点的高度,需要获得水量就是起点水量减去该点水量
                }
                for(int i=first+1;i<height.length;i++){
                    if(height[i]>height[first]){first=i;break;}//结束后,起点会往下走,找到比他要大的最近的一个点
                    first = i;
                }

                continue;
            }else if(height[first] == height[last]){
                //把中间给填平
                for(int i=first+1;i<last;i++){
                    if(height[i]<height[first]){
                        count+=height[first] -height[i];
                        height[i] = height[first];
                    }
                }
                System.out.println(count);
                //起点会找到最近的比他大的点,终点也会找到最近的比他大的点
                for(int i=first+1;i<height.length;i++){
                    if(height[i]>height[first]){first=i;break;}
                    first =i;
                }
                for(int i=last-1;i>=0;i--){
                    if(height[i]>height[last]){last = i;break;}
                    last = i;
                }
                continue;
            }else{
                //和第一种情况相似,这是起点高度小于重点高度
                for(int i=first+1;i<last;i++){
                    if(height[i]<height[last]){
                        count+=height[last] - height[i];
                        height[i] = height[last];
                    }
                }
                for(int i=last-1;i>=0;i--){

                    if(height[i]>height[last]){last=i;break;}
                    last = i;
                }
                continue;
            }
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值