一.问题描述
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.
二.我的解题思路
拿到这个题目,我开始的思路是寻找一个个凹槽,然后把它们给加起来。但是在实现的时候,在如何正确的划分一个凹槽上折腾了很久也没搞出来。我试图用if语句来分析所有可能的凹槽形状,但是难以解决本问题。随后借鉴了别人的思路,应该首先找到最大的bar。然后从两端向最大的bar逼近,这样可以确定凹槽的形状,接下来就好办了。
这套题也给我一些启发。思考问题需要一些大胆的尝试,我利用bar的下降来标识一个凹槽的开始,但是难以标识一个凹槽的结束。想法大胆一点的话,直接取最大值,那么就可以确定凹槽的形状了。
测试通过的程序如下:
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
if(n <= 2) return 0;
int max = -1, maxInd = 0;
int i = 0;
for(; i < n; ++i){
if(height[i] > max){
max = height[i];
maxInd = i;
}
}
int area = 0, root = height[0];
for(i = 0; i < maxInd; ++i){
if(root < height[i]) root = height[i];
else area += (root - height[i]);
}
for(i = n-1, root = height[n-1]; i > maxInd; --i){
if(root < height[i]) root = height[i];
else area += (root - height[i]);
}
return area;
}
};