42. Trapping Rain Water *HARD*
2016-03-05 23:30
337 查看
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
![](http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png)
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.
* The idea is:
* 1) find the highest bar.
* 2) traverse the bar from left the highest bar.
* becasue we have the highest bar in right, so, any bar higher than its right bar(s) can contain the water.
* 3) traverse the bar from right the highest bar.
* becasue we have the highest bar in left, so, any bar higher than its left bar(s) can contain the water.
For example,
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return
6.
![](http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png)
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.
int trap(int a[], int n) { int result = 0; //find the highest value/position int maxHigh = 0; int maxIdx = 0; for(int i=0; i<n; i++){ if (a[i] > maxHigh){ maxHigh = a[i]; maxIdx = i; } } //from the left to the highest postion int prevHigh = 0; for(int i=0; i<maxIdx; i++){ if(a[i] > prevHigh){ prevHigh = a[i]; } result += (prevHigh - a[i]); } //from the right to the highest postion prevHigh=0; for(int i=n-1; i>maxIdx; i--){ if(a[i] > prevHigh){ prevHigh = a[i]; } result += (prevHigh - a[i]); } return result; }
* The idea is:
* 1) find the highest bar.
* 2) traverse the bar from left the highest bar.
* becasue we have the highest bar in right, so, any bar higher than its right bar(s) can contain the water.
* 3) traverse the bar from right the highest bar.
* becasue we have the highest bar in left, so, any bar higher than its left bar(s) can contain the water.
相关文章推荐
- Android Studio中常用设置
- android 蓝牙锁应用实例开发(一) 简介
- android:theme常用相关属性值
- Android Studio 默认的快捷键
- 仿网易选项卡的实现
- 每个Xcode开发者应该知道的七个使用技巧
- IOS URL的缓存策略 分析
- 提高 Android 代码质量的4个工具
- android日常开发总结技术60条
- Cordova+ionic 开发hybird App --- 开发环境搭建
- 【Android】EditText获得焦点以及失去焦点
- gridview position =0多次调用getView, 如果有异步加载,那会导致程序效率低,并且导致position=0的控件显示有问题
- Object-c基础
- [Unity优化]unity中的优化方法
- Android使用 LruCache 缓存图片
- Objective-C 中 @property的使用
- Android 第三天重置版_注意事项
- Android中design包中的新控件2
- Android自定义点击下拉列表
- Improve Android App Performance