LeetCode 111 Trapping Rain Water

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.

For example,

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

LeetCode 111 Trapping Rain Water_第1张图片

分析:

对于每一格A[i],计算左边的最高沿left[i],再计算右边的最高沿right[i],根据木桶原理,这一格能存的水就是:

vol = min{left[i], right[i]} - A[i] > 0 ? min{left[i], right[i]} - A[i] : 0;

public class Solution {
    public int trap(int[] A) {
        if(A==null || A.length==0)
            return 0;
        int[] left = new int[A.length];
        int[] right = new int[A.length];
        //计算左边最大
        int max = A[0];
        for(int i=0; i<A.length; i++){
            if(A[i] <= max){
                left[i] = max;
            }else{
                left[i] = A[i];
                max = A[i];
            }
        }
        //计算右边最大
        max=A[A.length-1];
        for(int i=A.length-1; i>=0; i--){
            if(A[i] <= max){
                right[i] = max;
            }else{
                right[i] = A[i];
                max = A[i];
            }
        }
        //计算储水,0和A.length-1位置不算
        int vol = 0;
        for(int i=1; i<A.length-1; i++){
            //左右沿取最低
            int height = Math.min(left[i], right[i]);
            if(height > A[i]){
                vol += height-A[i];
            }
        }
        return vol;
    }
}


你可能感兴趣的:(LeetCode,water,Rain,Trapping)