lintcode-medium-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.

Trapping Rain Water

 

Example

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

Challenge

O(n) time and O(1) memory

O(n) time and O(n) memory is also acceptable.

 

public class Solution {
    /**
     * @param heights: an array of integers
     * @return: a integer
     */
    public int trapRainWater(int[] heights) {
        // write your code here
        
        if(heights == null || heights.length == 0)
            return 0;
        
        int[] left = new int[heights.length];
        int[] right = new int[heights.length];
        int res = 0;
        
        left[0] = 0;
        right[heights.length - 1] = 0;
        
        for(int i = 1; i < heights.length; i++)
            left[i] = Math.max(heights[i - 1], left[i - 1]);
        
        for(int i = heights.length - 2; i >= 0; i--)
            right[i] = Math.max(heights[i + 1], right[i + 1]);
        
        for(int i = 0; i < heights.length; i++){
            int height = Math.min(left[i], right[i]);
            
            if(height > heights[i])
                res += height - heights[i];
        }
        
        return res;
    }
}

 

posted @ 2016-04-07 12:08  哥布林工程师  阅读(129)  评论(0编辑  收藏  举报