42. 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.

42. Trapping Rain Water

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!

思路分析:从左至右,针对当前的高度,往右寻找,如果有大于等于当前高度的元素,则说明水平线应该拉到这儿,否则,应该找到在后面元素中相对最大的元素(如果有很多,则应该返回第一个元素)。cur指向这个返回的元素。

class Solution {
public:
int next(vector<int>& height, int pos){//若果pos位置后面有大于等于height[pos]直接返回第一个这样的值的位置,否则,返回后续中(最大的高度并且是第一次出现)的下标位置
if (pos >= height.size() - )//遍历到最后一个元素时,就应该结束了,因为蓄不了水
return -;
int val = height[pos];
int start = height[pos + ];
int res = pos + ;
for (int i = pos + ; i<height.size(); i++)
{
if (height[i] >= val){//情况之一,后面元素存在大于等于当前元素高度的值
return i;
}
else if (height[i]>start){//情况之二,记录后面元素中相对最大的元素,并且是第一次出现的元素
res = i;
start = height[i];
}
}
return res;
}
int trap(vector<int>& height) {
if(height.size()==)
return ;
int result = ;
int start = ;
while (height[start] == ){
start++;
}
while (start<height.size()-){
int cur = next(height, start);
int altitude = height[start]<height[cur] ? height[start] : height[cur];
for (int i = start + ; i<cur; i++){
result += (altitude - height[i]);
}
start = cur;
}
return result;
}
};
上一篇:Sicily 1048: Inverso(BFS)


下一篇:C# 使用网易邮箱发送邮件