Leetcode—— trapping-rain-water
来源:互联网 发布:云计算市场规模 编辑:程序博客网 时间:2024/06/05 07:08
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.
For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
解题思路:
类似于前述最大矩形解法,前为切头,此为填坑,异曲同工;
同理,可改为stack,复杂度为O(n): 将计算过的部分弹栈,认为其高度等于当前新水坝高度。
复杂度为O(n^2);
class Solution {public: int minn( int a, int b){ if( a < b){ return a; } return b; } int trap(int A[], int n) { //记录左侧水坝最大高度 //每次加入新水坝,判断是否满足蓄水条件(水坝高度是否大于前一个水坝) //更新储水量,并填坑。 //更新储水量:直至找到左侧最大高度的水坝或和当前水坝一样高的水坝 //填坑:为防止重复计算,将计算过的地方填平。 int sum = 0; int maxLeft = A[0]; for(int i= 1 ; i< n ; i++ ){ //满足蓄水条件 if( A[i] > A[i-1] ){ int cur = minn(maxLeft,A[i]); int cnt = 0; int k = i-1; while( A[k] < cur ){ cnt -= A[k]; A[k] = cur; k--; } cnt += cur * (i - k -1); sum += cnt; } //更新maxLeft; if( A[i] > maxLeft){ maxLeft = A[i]; } } return sum; }};
0 0
- LeetCode —— Trapping Rain Water
- LeetCode——Trapping Rain Water
- LeetCode题解——Trapping Rain Water
- leetcode 042 —— Trapping Rain Water
- Leetcode—— trapping-rain-water
- leetcode题集——trapping-rain-water
- LeetCode——Trapping Rain Water
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [LeetCode]Trapping Rain Water
- LeetCode-Trapping Rain Water
- [leetcode] Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- Leetcode:Trapping Rain Water
- Java语言基础1
- 关于链式表达式
- Git操作
- poj 2533 poj3903 poj1836 最长上升子序列 LIS
- 这些小工具让你的 Android 开发更高效(下)
- Leetcode—— trapping-rain-water
- [leetcode] 8. String to Integer (atoi)
- YTU 2335: 0-1背包问题
- FZU 2218 Simple String Problem
- Activity页面跳转
- CCNA实验练习
- Linux 游戏服务器搭建教程详解
- uml类图中关联与泛化的区别
- linux用户登录日志