当前位置:网站首页>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
总结
接雨水双指针最为优雅
边栏推荐
- 火山引擎入选国内首个《边缘计算产业全景图》
- GWD:基于高斯Wasserstein距离的旋转目标检测 | ICML 2021
- 为Golang项目编写Makefile
- Paging SQL (rownum, row_number, deny_rank, rank)
- C#学习一:值类型与引用类型
- Complex convolutional neural network: cv-cnn
- Three development trends of enterprise application viewed from the third technological revolution
- JS will have variable promotion and function promotion
- TDesign, which gave us benefits last time, will tell us its open source story today
- [data analysis] five common questions about learning SQL?
猜你喜欢

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

golang操作NSQ分布式消息队列

Interviewer: tell me about the MySQL transaction isolation level?

商业智能BI与业务管理决策思维之三:业务质量分析

动作捕捉系统用于苹果采摘机器人

Motion capture system for apple picking robot

京东联盟API - 万能转链接口 - 京品库接口 - 接口定制

GWD:基于高斯Wasserstein距离的旋转目标检测 | ICML 2021

Building SQL statements in Excel

three.js和高德地图结合引入obj格式模型-效果演示
随机推荐
Houdini图文笔记:VAT(3.0)导入UE4/5的设置向导[官方文档翻译]
云原生数据库查询优化-统计信息与行数估计
Is there any lack of dependence? An error is reported when flinksql is packaged and running, but there is no problem when the local idea runs. Solve it. Thanks
European standard plug en50075 test items
C language big job - Matching System
绑定证券账户到同花顺安全吗?哪家券商开户后可以绑定同花顺
Complex convolutional neural network: cv-cnn
LeetCode-64-最小路径和
【力扣10天SQL入门】Day7+8 计算函数
Kotlin annotation declaration and use
. Net program configuration file operation (INI, CFG, config)
Andorid Jetpack Hilt
C # learning 1: value type and reference type
MySQL scheduled full database backup & rolling deletion of backup data before the specified date
面试官:说一下MySQL事务隔离级别?
瓜分1000+万奖金池,昇腾AI创新大赛2022实力赋能开发者
商业智能BI与业务管理决策思维之三:业务质量分析
防范企业数据泄露,就用网络安全产品堡垒机!
2022年第一季度保险服务数字化跟踪分析
Where has lifeifei reached in his key "embodied intelligence"?