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.


對於每一個點來說,蓄水量 = min(左邊的最高點,右邊的最高點)-本身高度,於是兩次遍歷,一次用來找每個點的左邊的最高點,一次用來找每個點的右邊的最高點。


public class Solution {
    public int trap(int[] A) {
        int result = 0;
        if(A.length<3){
            return 0;
        }
        int []temp = new int[A.length];
        int left = A[0];
        for(int i=1;i<A.length-1;i++){
            if(A[i]<left){
                temp[i] = left;
            }else if(A[i]>left){
                left = A[i];
            }
        }
        int right = A[A.length-1];
        for(int i=A.length-2;i>0;i--){
            if(A[i]<right){
                if(temp[i]>0){
                    result += (min(temp[i],right)-A[i]);
                }
            }else if(A[i]>right){
                right = A[i];
            }
        }
        return result;
    }
      
    public int min(int a,int b){
        return a>b?b:a;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章