42. 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length <= 2) {
            return 0;
        }

        int leftMax = height[0], rightMax = height[height.length - 1];
        int left = 1, right = height.length - 2;
        int ret = 0;

        while (left <= right) {
            if (leftMax < rightMax) {
                ret += Math.max(0, leftMax - height[left]);
                leftMax = Math.max(leftMax, height[left++]);
            } else {
                ret += Math.max(0, rightMax - height[right]);
                rightMax = Math.max(rightMax, height[right--]);
            }
        }


        return ret;
    }
}
posted @ 2021-12-03 14:21  Tianyiya  阅读(22)  评论(0)    收藏  举报