Trapping Rain Water
2015-06-02 02:20
295 查看
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!
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!
class Solution { public: /** * @param heights: a vector of integers * @return: a integer */ int trapRainWater(vector<int> &heights) { // write your code here int n = heights.size(); if (n < 1) { return 0; } int result = 0; int rightMax ; rightMax[n-1] = heights[n-1]; for (int i = n-2; i >= 0; i--) { if (heights[i] > rightMax[i+1]) { rightMax[i] = heights[i]; } else { rightMax[i] = rightMax[i+1]; } } int begin = 0; while (begin < n && heights[begin] == 0) { begin++; } for (int i = begin+1; i < n; i++) { if (heights[i] >= heights[begin] || heights[i] == rightMax[i]) { int top = min(heights[i], heights[begin]); for (int j = begin+1; j < i; j++) { if (heights[j] < top) { result += (top - heights[j]); } } begin = i; } } return result; } };
相关文章推荐
- ASP.NET菜鸟之路之Application小例子
- UNITY 4.6.4 发行说明 中文版
- Mac 平台搭建 Android 集成开发环境
- Terminating app due to uncaught
- Android Studio 使用技巧(6)
- Android Studio 使用技巧(5)
- Android Studio 使用技巧(4)
- Android Studio 使用技巧(3)
- Android Studio 使用技巧(2)
- Android Studio 使用技巧(1)
- 关注Android安全 手机锁屏勒索国内首现身
- UNITY 4.6.5 发行说明 中文版
- cocos2dx——实现儿童节贺卡03
- Unity3D将来时:IL2CPP(下)
- cocos2dx——实现儿童节贺卡02
- <Unity UGUI>使用c#反射实现UGUI文本显示的国际化
- 用Unity制作游戏,你需要深入了解一下IL2CPP
- cocos2dx——实现儿童节贺卡01
- iOS 判断相册相机是否允许
- nokey属性(输出没有名称的数组)---精通android、IOS App应用服务程序开发