leetcode Trapping Rain Water

题目链接

trapping-rain-water

题目描述(Description)

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.

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!

分析(Analysis)

这道题放到了stack这一类里,然而一眼望过去这是一道数学几何体。

方法一(时间复杂度O(n))

从两边往中间扫描,对每一个`height[i]`来说,蓄水量等于左右两边第二高的柱子减去`height[i]`的值。最后把所有柱子的蓄水量加起来。

代码(Code)

方法一

class Solution {
public:
    int trap(vector<int>& height) {
        int ans=0;
        int len=height.size();
        int left=0,right=len-1,secHeight;
        while(left<right){
            if(height[left]<height[right]){
                secHeight=max(height[left],secHeight);
                ans+=secHeight-height[left];
                left++;
            }
            else{
                secHeight=max(height[right],secHeight);
                ans+=secHeight-height[right];
                right--;
            }
        }
        return ans;
    }
};