问题描述:
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.
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
解题思路
我们可以把所有的水看作是每一个凹槽里的水的总和。
凹槽总共有3中形式:左边界低于右边界的槽、两个边界相等的槽、左边界高于右边界的槽
正向遍历:统计出前两种槽的水量,如果height[i]<left则,改槽的水+=(left-height[i]) 直到height[i]>=left, 这时候到达该槽的右边界,再把里面的水放入vector里;
反向遍历:统计出左边界高于右边界的水,和正向遍历略有不同,我们从右往左看过来看就变成了前面一样的左低右高的槽,并且为了不重复,不统计left = height[i]这种槽的水
代码
class Solution {
public:int trap(vector<int>& height) {int sum =0;int len = height.size();if(len == 0) return 0;int left = height[0];vector<int> v;for(int i = 1; i<len;i++) //正向把所有左低右高或者左右一样高的槽的槽里的水算出来{if(left>height[i])sum+=(left-height[i]);else{v.push_back(sum);left = height[i];//更细槽sum = 0;} }left = height[len-1];sum = 0;for( int i = len-2; i>=0; i--) //反向遍历把两边左高右低的槽算出来{if(left>height[i])sum+=(left-height[i]);else if( left == height[i]) continue; //跳过左右一样高的槽else{v.push_back(sum);left = height[i];//更新槽sum = 0;} }sum = 0;for(int i = 0; i<v.size(); i++)sum+=v[i];return sum;}
};
时间复杂度:O(n)