leetcode hot100 42 接雨水 hard 双指针

记住就完了。。。

python 复制代码
当前的水=min(left_max[i], right_max[i]) - height[i]

先从左往右遍历一遍数组,求出每个位置左边最大的高度

再从右往左遍历一遍数组,求出每个位置右边最大的高度

最后,从左往右遍历数组,每个位置当前的水=min(left_max[i], right_max[i]) - height[i]

python 复制代码
class Solution:
    def trap(self, height: List[int]) -> int:
        n= len(height)

        if not height:
            return 0


         # 保存每个柱子左侧的最高柱子
        left_max = []  # 正向遍历时,不用[0]*n初始化也可以,直接append
        for i in range(0, n, 1):
            if i == 0:
                left_max.append(height[0])    # 第 0 个柱子左侧最高柱子就是它自己,没有更左边的柱子
            else:
                left_max.append(max(left_max[i-1], height[i]))


        #先初始化列表长度
        right_max = [0]*n

        for i in range(n-1, -1, -1):   # 从右往左 # range语法左闭右开,所以中间是-1才能扫到0
            if i==n-1:
                right_max[i] = height[-1]    # 最后一个柱子右侧最高柱子就是它自己,没有更右边的柱子
            else:
                right_max[i] = max([right_max[i+1], height[i]])


        # 计算积水
        water = 0
        for i in range(n):
            water += min(left_max[i], right_max[i]) - height[i]

        return water
相关推荐
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll2 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐2 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶3 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER3 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了3 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333333 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录3 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1233 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode