LeetCode:Trapping Rain Water
来源:互联网 发布:银川网络教育 编辑:程序博客网 时间:2024/05/17 02:18
算法很简单,核心思想是:对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i]。(均不包含自身)。如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。
有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight,在第二遍的同时就可以计算出i位置的结果了,而且并不需要开空间来存放rightMostHeight数组。
时间复杂度是O(n),只扫了两遍。
class Solution {public: int trap(int A[], int n) { //no way to contain any water if(n <= 2) return 0; //1. first run to calculate the heiest bar on the left of each bar int *lmh = new int[n];//for the most height on the left lmh[0] = 0; int maxh = A[0]; for(int i = 1; i < n; ++i) { lmh[i] = maxh; if(maxh < A[i]) maxh = A[i]; } int trapped = 0; //2. second run from right to left, // caculate the highest bar on the right of each bar // and calculate the trapped water simutaniously maxh = A[n-1]; for(int i = n - 2; i > 0; --i) { int left = lmh[i]; int right = maxh; int container = min(left,right); if(container > A[i]) { trapped += container - A[i]; } if(maxh < A[i]) maxh = A[i]; } delete lmh; return trapped; }};
0 0
- 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
- leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- LeetCode Trapping Rain Water
- LeetCode | Trapping Rain Water
- 29个月过去了,CSDN排名前200了:排名不断靠前的过程中,自己的技术水平和竞争力一定会不断向上
- Java线程面试题 Top 50
- poj1274
- gentoo时时更新官方安装教程地址中英文
- 解决虚拟键盘关闭后无法退出程序的问题
- LeetCode:Trapping Rain Water
- 重构—多种方法实现学生下机
- CocoaPods配置
- STM32的两只看门狗
- 站在“云”上——高校云平台项目总结
- C++ 再谈string类型(2) 修改string对象的方法
- codeforces 23E Tree (树形dp)
- 括号配对问题
- Windwos 7 环境下搭建Android Studio 开发环境