LeetCode 42 Trapping Rain Water
2016-03-24 07:01
615 查看
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!
根据输入的数组组成的直方图计算可以“盛水”的面积。idea是从第一个非零数开始标记为lastMarkedheight,这个lastMarkedheight作为一个可以盛水的高度基准,为了确定它是安全的,需要遍历它之后的数,要是有更高的数字则是安全的,否则把lastMarkedheight的值降低为可搜索到的最高高度。在确认安全之后继续遍历数组,遇到矮的则把高度差作为储水量加起来,遇到比lastMarkedheight高的就重新判断那个值是否安全并更新lastMarkedheight。
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!
根据输入的数组组成的直方图计算可以“盛水”的面积。idea是从第一个非零数开始标记为lastMarkedheight,这个lastMarkedheight作为一个可以盛水的高度基准,为了确定它是安全的,需要遍历它之后的数,要是有更高的数字则是安全的,否则把lastMarkedheight的值降低为可搜索到的最高高度。在确认安全之后继续遍历数组,遇到矮的则把高度差作为储水量加起来,遇到比lastMarkedheight高的就重新判断那个值是否安全并更新lastMarkedheight。
class Solution { public: int trap(vector<int>& height) { vector<int>::iterator it; int sumWater=0; int lastMarkedHight=0; for(it = height.begin();it!=height.end();it++){ if(lastMarkedHight==0 && *it == 0)//前面的0无视掉 continue; if(lastMarkedHight==0 && *it != 0){//第一个非零作为lastMarkedHight lastMarkedHight = *it; } if(lastMarkedHight!=0 && *it>=lastMarkedHight){//判断是否安全 int a = 0; bool findLarger = false; for(vector<int>::iterator tempIt=it+1;tempIt!=height.end();tempIt++){//找是否有更高的 if(*tempIt>*it){ findLarger = true; break; } } if(findLarger){//安全 lastMarkedHight = *it; continue; } else{//找it后最高的一个数作为lastMarkedHight while(find(it+1,height.end(),*it-a)==height.end() && *it-a>0){ a++; } lastMarkedHight = *it-a; } continue; } if(lastMarkedHight!=0 && *it<lastMarkedHight && it!=height.end()-1){ sumWater = sumWater+(lastMarkedHight-*it);//遇到矮的加储水量 cout<<sumWater<<endl; continue; } } return sumWater; } };
相关文章推荐
- Android 简单实现ListView顶部悬浮效果
- IOS键盘触摸退出总结
- 实现Android自定义ListView过程中出现的一些问题,要注意了,不能再犯!
- Android自定义控件系列案例【二】
- android学习——实现欢迎界面图片动画滑动切换
- iOS开发之NSRunLoop的进一步理解
- android学习——判断APP(程序)是否第一次启动
- Android学习之仿QQ侧滑功能的实现
- android中ListView控件&&onItemClick点击事件
- 【Android】Android Studio 1.5+ 中混合调试Native和Java代码
- 【Android】Android Studio 1.5+ 中混合调试Native和Java代码
- ios/swift上传代码到CocoaPods
- Android中使用java.util.Properties犯的错
- Cocos2dx Shader 使用系列之一:OpenGL Shader Language介绍
- ios-序列帧动画核心代码简单介绍以及封装
- iOS GCD不同场景的使用比较
- 开发错误记录6----友盟社会化分享与支付宝-微信支付问题
- Android开发 全面解析Activity生命周期
- ios-NSStringFromCGRect直接输出控件的frame
- Android监听——回调模式与观察者模式