[LintCode 363] 接雨水(Python)
来源:互联网 发布:qp个案分析比赛知乎 编辑:程序博客网 时间:2024/06/11 21:09
题目描述
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
样例
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.
思路
观察图片可知,接满雨水后,总体呈现先增后降的趋势。所以先遍历一遍,找到峰值的下标。再从两头向峰值遍历,不符合递增趋势的数值,都是需要计算填充差值的。
代码
class Solution: """ @param: heights: a list of integers @return: a integer """ def trapRainWater(self, heights): # write your code here if heights is None or len(heights) <= 2: return 0 max_id = 0 for i in range(1, len(heights)): if heights[i] > heights[max_id]: max_id = i res = 0 s = 0 cur = heights[s] while s < max_id: if heights[s] >= cur: cur = heights[s] else: res += 1 * (cur - heights[s]) s += 1 e = len(heights) - 1 cur = heights[e] while e > max_id: if heights[e] >= cur: cur = heights[e] else: res += 1 * (cur - heights[e]) e -= 1 return res
复杂度分析
时间复杂度
阅读全文
0 0
- [LintCode 363] 接雨水(Python)
- lintcode[363]:接雨水
- LintCode-接雨水
- LintCode:接雨水
- LintCode:接雨水
- 接雨水 lintcode
- LintCode:M-接雨水
- 接雨水-LintCode
- 接雨水 II-LintCode
- LintCode rain trap 接雨水
- 雨水,lintcode
- **[Lintcode]Trapping Rain Water 接雨水
- lintcode刷题——接雨水
- Trapping Rain Water 接雨水 python
- 接雨水
- 接雨水
- 接雨水
- 接雨水问题(C++)
- 设置背景图片随着浏览器缩放保持不变
- 递归的运行过程
- 1.5多媒体技术的应用领域
- CAS AtomicInteger 源码解析
- 第三周-项目四(2)顺序表的应用
- [LintCode 363] 接雨水(Python)
- 一、多媒体技术的基础本章小结
- 排序算法--Java实现直接插入排序
- HDU 1241 Oil Deposits(递归,搜索)
- taberror inconsistent use of tabs and spaces in indentation pycharm
- CentOS设置系统时间与网络时间同步
- CentOS7引导Win7
- ccf-有趣的数
- Mysql中查询某一天,某一月,某一年的数据