【LeetCode】#42接雨水(Trapping Rain Water)

【LeetCode】#42接雨水(Trapping Rain Water)

题目描述

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

Description

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.

Example

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

解法

class Solution {
    public static int trap(int[] height) {
        if(height.length<3){
            return 0;
        }
        int res = 0;
        int h1 = 0, h2 = 0;
        int t1 = 0, t2 = 0;
        for(int i=0; i<height.length; i++){
//        	System.out.println("h1="+h1+", h2="+h2+", height["+i+"]="+height[i]);
            if(h1==0 && height[i]>h1){
            	h1 = height[i];
                t1 = i;
            }else if(h1!=0 && height[i]>=h1 && height[i-1]<h1){
                h2 = height[i];
            	t2 = i;
            }else if(h1!=0 && height[i]>=h1 && height[i-1]==h1){
            	h1 = height[i];
            	t1 = i;
            }
            if(h1!=0 && h2!=0){
                res += helper(height, t1, t2, Math.min(h1,h2));
                h1 = 0;
                h2 = 0;
                i--;
            }
        }
//        System.out.println();
        int t3 = 0;
        t2 = 0;
        int h3 = 0;
        h2 = 0;
        for(int i=height.length-1; i>=t1; i--){
//        	System.out.println("h2="+h2+", h3="+h3+", height["+i+"]="+height[i]);
        	if(h3==0 && height[i]>h3){
        		h3 = height[i];
        		t3 = i;
        	}else if(h3!=0 && height[i]>=h3 && height[i+1]<h3){
        		h2 = height[i];
        		t2 = i;
        	}else if(h3!=0 && height[i]>=h3 && height[i+1]==h3){
        		h3 = height[i];
        		t3 = i;
        	}
        	if(h2!=0 && h3!=0){
        		res += helper(height, t2, t3, Math.min(h2,h3));
        		h2 = 0;
        		h3 = 0;
        		i++;
        	}
        }
        return res;
    }
    
    public static int helper(int[] height, int t1, int t2, int min){
//    	System.out.println("t1="+t1+", t2="+t2+", min="+min);
        int res = 0;
        for(int i=t1+1; i<t2; i++){
            res += (min-height[i]);
        }
//        System.out.println("res+="+res);
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84843715