[LeetCode] Trapping Rain Water 解题报告
2016-01-12 11:09
483 查看
Given n[/i] 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://codingtmd.azurewebsites.net/wp-content/uploads/2013/01/rainwatertrap-300x117.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.Thanks Marcos[/b] for contributing this image!
» Solve this problem
[解题思路]
对于任何一个坐标,检查其左右的最大坐标,然后相减就是容积。所以,
1. 从左往右扫描一遍,对于每一个坐标,求取左边最大值。
2. 从右往左扫描一遍,对于每一个坐标,求最大右值。
3. 再扫描一遍,求取容积并加和。
#2和#3可以合并成一个循环,
如果我是面试官的话,在这里可以加一个变形。不求所有容积,而是求容积中的最大值。这样就类似于Container With Most Water,[/b]但是又有不同的地方。这题里面每一个坐标本身是占体积的。所以从两边往中间扫的时候,根本不知道中间坐标共占用了多少体积。
For example,
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return
6.
![](http://codingtmd.azurewebsites.net/wp-content/uploads/2013/01/rainwatertrap-300x117.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.Thanks Marcos[/b] for contributing this image!
» Solve this problem
[解题思路]
对于任何一个坐标,检查其左右的最大坐标,然后相减就是容积。所以,
1. 从左往右扫描一遍,对于每一个坐标,求取左边最大值。
2. 从右往左扫描一遍,对于每一个坐标,求最大右值。
3. 再扫描一遍,求取容积并加和。
#2和#3可以合并成一个循环,
[code]1: int trap(int A[], int n) { 2: // Start typing your C/C++ solution below 3: // DO NOT write int main() function 4: if(n<2) return 0; 5: int *maxL = new int , *maxR=new int ; 6: int max = A[0]; 7: maxL[0] =0; 8: for(int i =1; i<n-1; i++) 9: { 10: maxL[i] =max; 11: if(max < A[i]) 12: max = A[i]; 13: } 14: max=A[n-1]; 15: maxR[n-1]=0; 16: int ctrap,ttrap=0; 17: for(int i = n-2; i>0; i--) 18: { 19: maxR[i] = max; 20: ctrap = min(maxL[i], maxR[i]) -A[i]; 21: if(ctrap>0) 22: ttrap+=ctrap; 23: if(max<A[i]) 24: max = A[i]; 25: } 26: delete maxL, maxR; 27: return ttrap; 28: }
如果我是面试官的话,在这里可以加一个变形。不求所有容积,而是求容积中的最大值。这样就类似于Container With Most Water,[/b]但是又有不同的地方。这题里面每一个坐标本身是占体积的。所以从两边往中间扫的时候,根本不知道中间坐标共占用了多少体积。
相关文章推荐
- MVP模式在android的使用
- android中的AIDL进程间通信
- Android获取Manifest中<meta-data>元素的值
- App的运行内存占用问题
- Android 之 Fresco 显示圆形图片 之坑
- Attribute is missing the Android namespace prefix(属性是失踪的Android名称空间前缀)
- 数组存取基本数据类型
- cocos2d-x引擎
- 如何完善MindMapper导图到表格的格式问题
- Android px、dp、sp之间相互转换
- android不错的学习网址
- 42. Trapping Rain Water
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Appstore proj: Calculate an App's Top-5 related apps(1)
- ios购物车的实现
- Android studio 快捷键大全
- iOS平台下cookie的使用
- android:id="@android:id/tabhost" 、android:id="@+id/llRoot" 、android:id="@id/llRoot" 之间的区别
- Android开发之资源目录assets与res/raw的区别分析
- iOS开发之OC命名规范和编码规范(持续更新)