Leetcode专题-42-接雨水

LabRat / 168 /

ChatGPT 可用网址,仅供交流学习使用,如对您有所帮助,请收藏并推荐给需要的朋友。
https://ckai.xyz

力扣链接:
https://leetcode.cn/problems/trapping-rain-water/description/
解题思路:
给定一个数组height,其中height[i]表示第i个位置的高度,假设它构成的图形是一个容器,求这个容器能够接住多少雨水。代码使用双指针的方式,从数组的两端开始向中间移动,维护左边和右边的最高柱子分别为leftMax和rightMax。在移动指针的过程中,如果左边的柱子比右边的柱子低,则说明左边的柱子可能会挡住右边的柱子,此时计算左边的柱子能够接住多少水,并将leftMax更新为当前柱子的高度。如果右边的柱子比左边的柱子低,则说明右边的柱子可能会挡住左边的柱子,此时计算右边的柱子能够接住多少水,并将rightMax更新为当前柱子的高度。最终返回能够接住的雨水总量

func trap(height []int) int {
    var left, right, leftMax, rightMax, res int
    right = len(height) - 1
    for left < right {
        if height[left] < height[right] {
            if height[left] >= leftMax {
                leftMax = height[left]  // 设置左边最高柱子
            } else {
                res += leftMax - height[left]  // //右边必定有柱子挡水,所以遇到所有值小于等于leftMax的,全部加入水池中
            }
            left++
        } else {
            if height[right] > rightMax { 
                rightMax = height[right]  // //设置右边最高柱子
            } else {
                res += rightMax - height[right]  // //左边必定有柱子挡水,所以,遇到所有值小于等于rightMax的,全部加入水池
            }
            right--
        }
    }
    return res
}

作者
LabRat
许可协议
CC BY 4.0
发布于
2023-09-02
修改于
2025-02-12
Bonnie image
尚未登录