LeetCode - #42 接雨水(Top 100)

前言

本题为 LeetCode 前 100 高频题

我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。微博:@故胤道长)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新了 41 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。

不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:困难

1. 描述

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

2. 示例

示例 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 * 10^4
  • 0 <= height[i] <= 10^5

3. 答案

class TrappingRainWater {
    
    
    func trap(height: [Int]) -> Int {
    
    
        guard height.count > 0 else {
    
    
            return 0
        }
        
        var res = 0
        var left = _initMaxHeights(height, true)
        var right = _initMaxHeights(height, false)
        
        for i in 0..<height.count {
    
    
            res += min(left[i], right[i]) - height[I]
        }
        
        return res
    }
    
    private func _initMaxHeights(height: [Int], _ isLeft: Bool) -> [Int] {
    
    
        var res = [Int](count: height.count, repeatedValue: 0)
        var currentMax = 0
        
        if isLeft {
    
    
            for i in 0..<height.count {
    
    
                res[i] = max(currentMax, height[I])
                currentMax = res[I]
            }
        } else {
    
    
            for i in (0..<height.count).reverse() {
    
    
                res[i] = max(currentMax, height[I])
                currentMax = res[I]
            }
        }
        
        return res
    }
}
  • 主要思想:雨容总是由左右最大高度的最小值决定的。
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

该算法题解的仓库:LeetCode-Swift

点击前往 LeetCode 练习

关于我们

我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。

猜你喜欢

转载自blog.csdn.net/qq_36478920/article/details/125063191