Golang | Leetcode Golang题解之第42题接雨水

题目:

题解:

Go 复制代码
func trap(height []int) (ans int) {
    n := len(height)
    if n == 0 {
        return
    }

    leftMax := make([]int, n)
    leftMax[0] = height[0]
    for i := 1; i < n; i++ {
        leftMax[i] = max(leftMax[i-1], height[i])
    }

    rightMax := make([]int, n)
    rightMax[n-1] = height[n-1]
    for i := n - 2; i >= 0; i-- {
        rightMax[i] = max(rightMax[i+1], height[i])
    }

    for i, h := range height {
        ans += min(leftMax[i], rightMax[i]) - h
    }
    return
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
相关推荐
Swift社区3 小时前
LeetCode 421 - 数组中两个数的最大异或值
算法·leetcode·职场和发展
Kuo-Teng6 小时前
LeetCode 206: Reverse Linked List
java·算法·leetcode·职场和发展
做怪小疯子10 小时前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
Dream it possible!10 小时前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
做怪小疯子10 小时前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
sin_hielo11 小时前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi11 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣11 小时前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽11 小时前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
stand_forever13 小时前
PHP客户端调用由Go服务端GRPC接口
rpc·golang·php