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.
测试代码:
class Solution {
public:
int trap(vector<int>& height) {
int left = 0,right = height.size()-1;
int moment = 0;
int sum = 0;
while(left<right)
{
moment =max(moment,min(height[right],height[left]));
if(height[right]>=height[left])
{
if(moment>height[left])
sum = sum+moment-height[left];
left++;
}else{
if(moment>height[right])
sum = sum+moment-height[right];
right--;
}
}
return sum;
}
};
性能:
参考答案:
class Solution {
public:
int trap(vector<int>& height) {
if(height.size() < 3)
return 0;
int left = 0;
int leftMax = 0; //local max value from left
int right = height.size() - 1;
int rightMax = 0; //local max value from right
int result = 0; //result is an accumulation value. add value to it during each loop, which means we don't calculate it
//directly, we calculate it at each point. the gap between local max and height at that point is the
while(left < right)//capacity at that point. we add it to result, so the total result is the final result. and only if
{ //left can meet right, we have scaned all the points. and using two pointers can avoid wrong results
//in triangle arrays, such as[1,2,3,4,3,2,1].
leftMax = max(leftMax, height[left]); //get the local max value at current heights
rightMax = max(rightMax, height[right]);
if(height[left] < height[right]) //if height[left] < height[right] means we shoud move the left
{
result += leftMax - height[left]; //add the gap between leftMax and height[left], it is the water capacity at
++left; //this point.
}
else
{
result += rightMax - height[right];
--right;
}
}
return result;
}
};