42.接雨水 python3
2019-10-09 20:00
106 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35857125/article/details/102468775
题目:
解析:
这道题有两类解法,横向和纵向。
- 纵向:只需要求解左边的最高值和右边的最高值,两者中较小的一个减去当前的高度,即为当前格子纵向的雨水量。
- 横向:如果当前的格子高度大于前一个,小于前面第二个,则可以确定前一个的一段横向的积水量。
代码:
class Solution: def trap(self, height: List[int]) -> int: stack = [] rain = 0 for i in range(len(height)): while len(stack) >= 2 and height[stack[-1]] < height[i]: rain = rain + (min(height[stack[-2]], height[i]) - height[stack[-1]]) * (i - stack[-2] - 1) stack.pop() if len(stack) == 1 and height[i] > height[stack[-1]]: stack.pop() stack.append(i) return rain
小结:
栈是一种思想,而不仅仅是一种数据结构。
相关文章推荐
- 【问题】【python】_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h'
- 笨方法学python 42课笔记:物以类聚
- 笨办法学python 42
- Python-Project Euler 42
- win7 64 安装mysql-python:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
- 笨方法学习Python-习题42: 物以类聚
- Python内置函数(42)——memoryview
- LeetCode || 42. 接雨水
- LeetCode--Trapping Rain Water(捕获雨水)Python
- (Python mysql驱动的解决)_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h':问题的解决
- Python内置函数(42)——hash
- Python-MySQLdb _mysql.c(42)错误
- Learn Python The Hard Way exercise 42
- /hue/hue/Makefile.vars:42: *** "Error: must have python development packages for 2.6 or 2.7. Could n
- 笨办法学 Python · 续 练习 42:SQL 删除
- Python单例模式的4种实现方法 分类: python学习 2015-05-08 16:49 42人阅读 评论(0) 收藏
- Python3网络爬虫实战-42、图形验证码的识别
- Python 小甲鱼教程 课后练习42
- Python 3基础教程42-锁
- win7 64 安装mysql-python:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': N