Trapping Rain Water
2013-10-29 11:07
253 查看
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
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!
对某个值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数组。代码如下:
For example,
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return
6.
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!
对某个值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数组。代码如下:
class Solution { public: int trap(int A[], int n) { //no way to contain any water if(n <= 2) { return 0; } else { //1. first run to calculate the heiest bar on the left of each bar int *lmh = new int[n + 5];//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; } } };
相关文章推荐
- 浏览器中打开IOS应用并传参
- cocos2d权威指南部分摘录
- iOS 7开源项目干货集合
- web.xml中servlet-mapping的配置
- android 中把一个activity 转换成一个view
- UIWebView相关
- Trapping Rain Water
- iOS企业级开发者计划的申请流程
- Android 中Webview 自适应屏幕
- ANDROID笔记:Activity之间的传值
- [zz]android的logcat详细用法
- Android系统手机端抓包方法
- 微信公众号开发第一课 预备知识和申请权限账号
- Android API 指南
- cocos2d-x场景中的层(CCLayer)及其触摸消息响应(转)
- 【Cocos2d-x游戏引擎开发笔记(6)】触屏事件与多媒体 (转)
- Android的Touch Mode
- Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootI
- Android开发之日历控件实现
- [unity3d]链接mysql的Project build出错