当前位置:网站首页>leetcode:42. 接雨水【双指针很优雅】
leetcode:42. 接雨水【双指针很优雅】
2022-06-29 15:37:00 【白速龙王的回眸】

分析
双指针从最左最右开始
一个个比较height,如果当前这个小就往内移动
用leftMax和rightMax记录左右两边遍历过的最大的值
要知道的是,当前移动的那一端,一定是被比下去的,也就是说当前没移动的那一个点一定是目前最大的
因此比如左边移动了,它这个一定会被leftMax和height[j]包围,并且leftMax一定是小的,所以贡献就是leftMax - height[i]
ac code
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
i, j = 0, len(height) - 1
leftMax, rightMax = height[0], height[-1]
ans = 0
while i <= j:
leftMax = max(leftMax, height[i]) # 左边max
rightMax = max(rightMax, height[j]) # 右边max
# 中间ij判断
if height[i] < height[j]:
# height[i]被leftmax和height[j]夹着,leftmax更小(不然不会挪走)
ans += leftMax - height[i]
i += 1
else:
# height[j]被rightmax和height[i]夹着,rightmax更小(不然不会挪走)
ans += rightMax - height[j]
j -= 1
return ans
总结
接雨水双指针最为优雅
边栏推荐
- MySQL scheduled full database backup & rolling deletion of backup data before the specified date
- 【云原生】Nacos-TaskManager 任务管理的使用
- 89.(cesium篇)cesium聚合图(自定义图片)
- swoole TCP 分布式实现
- Stlink troubleshooting
- Rust Basics
- Business Intelligence BI and business management decision-making thinking No. 3: business quality analysis
- 89. (cesium article) cesium aggregation diagram (custom picture)
- postgresql源码学习(25)—— 事务日志⑥-等待日志写入完成
- postgresql源码学习(24)—— 事务日志⑤-日志写入WAL Buffer
猜你喜欢

C # learning 1: value type and reference type

发明了杀毒软件之后,他选择做一个极品混混

stlink故障修复
[data analysis] five common questions about learning SQL?

C#学习二:堆和栈

89.(cesium篇)cesium聚合图(自定义图片)

89. (cesium article) cesium aggregation diagram (custom picture)

Huawei cloud AOM version 2.0 release

Andorid Jetpack Hilt

golang操作NSQ分布式消息队列
随机推荐
Cmake learning-2
89.(cesium篇)cesium聚合图(自定义图片)
golang操作etcd
ROS2机器人f1tenth之CLI工具基础
华为云AOM 2.0版本发布
postgresql源码学习(23)—— 事务日志④-日志组装
File common tool class, stream related application (record)
swift JSONSerialization
【crossbeam系列】5 crossbeam-util和crossbeam-queue:一些实用的小东西
C # learning 1: value type and reference type
Flink SQL task taskmanager memory settings
Polarimetric SAR surface classification
wallys/m.2/Adapter card(one pcie1x to 4 x Mini PCIE)
89. (cesium article) cesium aggregation diagram (custom picture)
Huawei cloud AOM version 2.0 release
墨天轮“高可用架构”干货文档分享(含Oracle、MySQL、PG资料124篇)
MySQL scheduled full database backup & rolling deletion of backup data before the specified date
TDesign, which gave us benefits last time, will tell us its open source story today
Andorid Jetpack Hilt
PostgreSQL source code learning (23) -- transaction log ④ - log assembly