码迷,mamicode.com
首页 > 移动开发 > 详细

lintcode-medium-Trapping Rain Water

时间:2016-04-07 13:27:55      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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

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;
    }
}

 

lintcode-medium-Trapping Rain Water

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5362953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!