当前位置:网站首页>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
总结
接雨水双指针最为优雅
边栏推荐
- 12.udp protocol -bite
- taro3.*中使用 dva 入门级别的哦
- Scroll, do you understand?
- 如何用好数据科学?
- wallys/m.2/Adapter card(one pcie1x to 4 x Mini PCIE)
- 【云原生】Nacos-TaskManager 任务管理的使用
- stlink故障修复
- . Net program configuration file operation (INI, CFG, config)
- What is the time complexity of the redis command?? (the actual question is about the underlying structure of redis)
- El table column row button anti weight control loading
猜你喜欢

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

Classe d'outils commune de fichier, application liée au flux (enregistrement)

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

MySQL XA distributed transaction

What are the advantages of intelligent chat robots? Senior independent station sellers tell you!

Building SQL statements in Excel

Paging SQL (rownum, row_number, deny_rank, rank)

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

Motion capture system for apple picking robot

Business Intelligence BI and business management decision-making thinking No. 3: business quality analysis
随机推荐
Autodesk Revit 2023软件安装包下载及安装教程
C language homework - matching system
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
Where has lifeifei reached in his key "embodied intelligence"?
C SQLite class library
Taro 小程序开启wxml代码压缩
golang操作etcd
欧标插头EN50075测试项目
Kotlin annotation declaration and use
Digital tracking analysis of insurance services in the first quarter of 2022
关于 麒麟系统启动应用报错“undefined symbol: __cxa_throw_bad_array_new_length, version Qt_5“ 的解决方法
Houdini图文笔记:VAT(3.0)导入UE4/5的设置向导[官方文档翻译]
radar transmitter
PostgreSQL source code learning (25) -- transaction log ⑥ - wait for log writing to complete
华为云AOM 2.0版本发布
What is the time complexity of the redis command?? (the actual question is about the underlying structure of redis)
R语言DALEX包的explain函数生成指定分类预测机器学习模型解释器、predict_parts函数基于oscillations方法分析对于指定的某一条样本、每个变量对于预测结国的贡献程度
商业智能BI与业务管理决策思维之三:业务质量分析
When easygbs calls the interface for obtaining real-time snapshots, how to solve the problem of white squares?
Numpy 的研究仿制 1