42. Trapping Rain Water
2015-12-21 22:31
375 查看
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. Thanks Marcos for contributing this image!
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. Thanks Marcos for contributing this image!
class Solution { public: int trap(vector<int>& height) { if(height.size() < 3) return 0; int res = 0; int left = 0; int right = height.size() - 1; int leftMax = height[0]; int rightMax = height[right]; while(left != right){ if(leftMax < rightMax){ left++; if(height[left]<leftMax){ res +=leftMax - height[left]; }else{ leftMax = height[left]; } }else{ right--; if(height[right] < rightMax){ res += rightMax- height[right]; }else{ rightMax = height[right]; } } } return res; } };
相关文章推荐
- IOS沙盒Files目录说明和常用操作
- 【Android测试】【第一节】性能——CPU
- android之旅1:background && hello world
- [LeetCode] 42. Trapping Rain Water 解题思路
- 解决android sdk 无法更新
- 微信生态圈盈利模式分析
- Android中killProcess()、System.exit(0)及finish()的区别
- UIApplication的小结
- android开发步步为营之89:ListView和GridView动态加载图片,保证不导致OOM
- Swift 命名规则
- 在iOS中使用icon font
- android shape的使用
- Mars 老师 Android 教程之 Activity 生命周期学习笔记
- 在android studio中导入开源库PullToRefresh
- iOS开发拓展篇—CoreLocation定位服务
- cocos2dx怎样设置ios和Android横屏竖屏的几种方法
- iOS屏幕尺寸和分辨率了解
- Android内存泄露
- android实现课程表界面
- App store 发布,64位问题,Missing 64-bit support