2014年4月14日 星期一

[LeetCode] Trapping Rain Water

Problem:
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.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 
Solution:O(n)
public class Solution {
    public int trap(int[] A) {
        int ret = 0;
        if(A.length<3) 
           return ret;
         
        int[] left = new int[A.length-2],
           right = new int[A.length-2];
         
        for(int i=0;i<A.length-2;i++)
          left[i]=i>0?Math.max(left[i-1],A[i]):A[i];
         
        for(int i=A.length-3;i>=0;i--)
          right[i]=i<A.length-3?Math.max(right[i+1],A[i+2]):A[i+2];
         
        for(int i=0;i<A.length-2;i++){
          int tmp= Math.min(left[i],right[i]);
          if(temp>A[i+1])
             ret+=tmp-A[i+1];
        }
        return ret;
    }
}
Key Concept:From each point see the left side and right side to determine water

沒有留言:

張貼留言