码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 42. 接雨水

时间:2018-07-20 00:26:28      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:leetcode   trap   problem   app   solution   https   esc   mat   min   

42. 接雨水

思路:一块柱子能接水的量取决于它左右两边最高的柱子中较短的一个。

class Solution {
    public int trap(int[] height) {
        int left[] = new int[height.length];
        int right[] = new int[height.length];
        int max = 0;
        for (int i = 0; i < height.length; i++) {
            max = Math.max(max, height[i]);
            left[i] = max;
        }
        max = 0;
        for (int i = height.length - 1; i >= 0; i--) {
            max = Math.max(max, height[i]);
            right[i] = max;
        }

        int ans = 0;
        for (int k = 1; k < height.length - 1; k++) {
            if (left[k - 1] <= 0 || right[k + 1] <= 0) continue;
            int tmp = Math.min(left[k - 1], right[k + 1]) - height[k];
            if (tmp > 0) ans += tmp;
        }

        return ans;
    }
}

[leetcode] 42. 接雨水

标签:leetcode   trap   problem   app   solution   https   esc   mat   min   

原文地址:https://www.cnblogs.com/acbingo/p/9339010.html

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