您的位置:首页 > 移动开发

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
[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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: