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!
这道题和container with most water 有点类似,但是这道题更难一点;分析题目可看出,随意给定一组数字,可能形成很多个"坑",那么是否可以每次计算出一个坑中的水,最后将其相加得到最终结果。
用递归是容易做到的,每次找出两个最高的bar,然后计算这两个bar之间的水量,再分别在其左边和右边递归的进行寻找。
class Solution {
public:
int trap(vector<int>& height) {//用递归可以实现
if(height.size()<3) return 0;
int maxidxI=0,maxidxJ=height.size()-1;
int temp,water = 0;
for(int i=1;i<height.size()-1;i++)
{
if(height[i]>height[maxidxI])
maxidxI = i;
}
for(int i =height.size()-1;i>=0;i--)
{
if(height[i]>height[maxidxJ] && i!=maxidxI)
maxidxJ = i;
}
if(maxidxI>maxidxJ)
{
int t = maxidxI;
maxidxI =maxidxJ;
maxidxJ =t;
}
temp =0;
for(int m = maxidxI+1 ; m<= maxidxJ-1; m++)
temp+= height[m];
water+=(height[maxidxI]>height[maxidxJ]?height[maxidxJ]:height[maxidxI])*(maxidxJ - maxidxI -1) - temp;
vector<int> l(height.begin(),height.begin()+maxidxI+1),r(height.begin()+maxidxJ,height.end());
return water+trap(l)+trap(r);
}
};