Leetcode 42. Trapping Rain Water

本文介绍了一种计算雨后地面积水总量的方法。通过记录每根柱子左侧和右侧已见过的最大高度,我们可以确定每根柱子能留住多少雨水。算法使用两个数组分别从左到右和从右到左遍历,最终计算出总的积水体积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * To sum up total trapping water, we need to know how many water can be trapped by each bar after raining.
 * The amount of trapping water for each bar is calculated by min(maxSeenLeft, maxSeenRight) - currentBarHeight.
 * We will need an array to save the max height seen from right to left,
 * and set the maxSeenLeft as 0, increase it each time we see and larger height, 
 * sum each bar's trapping water by min(maxSeenLeft, maxSeenRight) - currentBarHeight.
 */ 
public class Solution {
    public int trap(int[] height) {
        if (height == null || height.length == 0 || height.length == 1) {
            return 0;
        }
        
        // Save the max height seen so far from right to left
        int currMax = height[height.length-1];
        int[] maxRight = new int[height.length];
        maxRight[height.length-1] = currMax;
        for (int i=height.length-2; i>=0; i--) {
            if (height[i] > currMax) {
                currMax = height[i];
            }
            maxRight[i] = currMax;
        }
        
        // From left to right, calculate each bar's trapping water
        int maxWater = 0;
        int maxLeft = 0;
        for (int j=0; j<height.length; j++) {
            maxWater += Math.max(Math.min(maxLeft, maxRight[j]) - height[j], 0);
            // Update max height seen so far from left to right
            if (height[j] > maxLeft) {
                maxLeft = height[j];
            }
        }
        
        return maxWater;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值