LeetCode Logo

42. 接雨水

https://leetcode.cn/problems/trapping-rain-water/description

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

示例 1:

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

思路:双指针左右夹逼,动态维护左右最高柱,谁低谁动,水量公式=谁低的最高柱-当前柱高

C#实现:

public class Solution {
    public int Trap(int[] height) {
        int n = height.Length;
        if(n == 0) return 0;
        int res = 0;
        int left = 0, right = n - 1;
        int lMax = 0, rMax = 0;
        // 双指针从两边向中间移动
        while(left <= right) {
            // 更新左右最高柱
            lMax = Math.Max(lMax, height[left]);
            rMax = Math.Max(rMax, height[right]);
            // 判断那一侧的柱更低,谁更低,就确定了积水量
            if(lMax < rMax) {
                // 当前柱积水量 = 左柱最高 - 当前柱度
                res += lMax - height[left];
                // 向右移动继续处理下一个位置
                left++;
            } else {
                // 当前柱积水量 = 右柱最高 - 当前柱度
                res += rMax - height[right];
                // 向左移动继续处理下一个位置
                right--;
            }
        }
        return res;
    }
}

Subscribe for New Articles!

Leave a Comment

Your email address will not be published. Required fields are marked *