首页 > 移动平台 > 详细

[LeetCode]42 Trapping Rain Water

时间:2015-01-02 07:31:19      阅读:462      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/trapping-rain-water/

http://fisherlei.blogspot.com/2013/01/leetcode-trapping-rain-water.html


public class Solution {
    public int trap(int[] A) {
            
        // 对于某坐标 有
        // - leftmax 它左边最高
        // - rightmax 它右边最高
        // - val 它本身高度
        // 那么它的容积为 max( min(leftmax, rightmax) - val, 0 )
        
        // 那么从左向右遍历 创建 leftmax[]
        // 类似 从右向左遍历 创建 rightmax[]
        // 最后遍历一遍 计算容积 求和
        // O(n)
        
        // Input validations.
        if (A == null || A.length == 0)
            return 0;   // Invalid input.
        
        int len = A.length;
        
        // Build leftmax[]
        int[] leftmax = new int[len];
        int seenleftmax = 0;
        for (int i = 0 ; i < len ; i ++)
        {
            leftmax[i] = seenleftmax;
            if (A[i] > seenleftmax)
                seenleftmax = A[i];
        }
        
        // Build rightmax[]
        int[] rightmax = new int[len];
        int seenrightmax = 0;
        for (int i = len - 1 ; i >= 0 ; i --)
        {
            rightmax[i] = seenrightmax;
            if (A[i] > seenrightmax)
                seenrightmax = A[i];
        }
        
        // Calculate result
        int result = 0;
        for (int i = 0 ; i < len ; i ++)
        {
            int v = Math.max(Math.min(leftmax[i], rightmax[i]) - A[i] , 0);
            result += v;
        }
        return result;
    }
}


[LeetCode]42 Trapping Rain Water

原文:http://7371901.blog.51cto.com/7361901/1598372

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!