LeetCode 42 - Trapping Rain Water
2016-03-03 12:36
513 查看
Trapping Rain Water
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
[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!
My Two Pass Code
class Solution { public: int trap(vector<int>& height) { int size = height.size(); int start = 0, end = size - 1; int total = 0; // Left to right for (int i = 1; i < size; i++) { if (height[i] >= height[start]) { if (i == start + 1) start= i; else { end = i; // Caculate int s = min(height[start], height[end]) * (end - start - 1); cout << start << " " << end << " " << s << endl; for (int j = start + 1; j < end; j++) s -= height[j]; total += s; start = end; } } } // Right to left start = size - 1, end = 0; for (int i = size - 2; i >= 0; i--) { if (height[i] > height[start]) { if (i == start - 1) start= i; else { end = i; // Caculate int s = min(height[start], height[end]) * (start - end - 1); for (int j = start - 1; j > end; j--) s -= height[j]; total += s; start = end; } } } return total; } };
Runtime: 20 ms
My One Pass Code
class Solution { public: int trap(vector<int>& height) { int size = height.size(); int start = 0, end = size - 1; int max_left_height = 0, max_right_height = 0; int total = 0; while (start <= end) { if (height[start] <= height[end]) { if (height[start] <= max_left_height) total += max_left_height - height[start]; else max_left_height = height[start]; start++; } else { if (height[end] <= max_right_height) total += max_right_height - height[end]; else max_right_height = height[end]; end--; } } return total; } };Runtime: 8 ms
相关文章推荐
- ios获取当前的时间
- 进入Android Dalvik虚拟机之Dalvik指令集
- ios之TableViewCell重用机制避免重复显示问题
- android xml解析 XmlPullParser的使用
- Android之NFC手机读取银行卡信息
- iOS每日一记-----------之 一个弹框View
- Android5.0-新特性
- Android Studio的学习
- Android studio图片ERROR: 9-patch image xx .9.png malformed
- 微信企业号开发开启回调模式
- iOS开发-运行循环
- 改变导航栏
- Android性能优化之Activity 泄漏
- swift 快速奔跑的兔几 本节的内容是:iOS上基于文档的应用程序
- 使用OClint进行iOS项目的静态代码扫描
- Android中如何让DialogFragment全屏(DialogFragment fullscreen)
- iOS Gif图片展示N种方式(原生+第三方)
- iOS 中KVC、KVO、NSNotification、delegate 总结及区别
- Android之带group指示器的ExpandableListView
- Android布局优化之Merge、Include、ViewStub使用与源码分析