Leetcode 42. Trapping Rain Water

42. Trapping Rain Water

题目链接:https://leetcode.com/problems/trapping-rain-water/

Description:

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

题意:

如图,给出一些墙的高度,问最多能承装的水是多少。

题解:

维护一个非递增栈,为了方便起见,压入栈中的为坐标。

如果当前高度大于栈顶的高度,那么我们就将栈顶弹出,根据下一个栈顶来确定对答案的贡献。如果此时栈为空,那么对答案就没有贡献。

如果高度相同的在栈中,对答案是没有贡献的,符合题意。

代码如下:

class Solution {
public:
    int trap(vector<int>& height) {
        int i=0;
        int n = height.size();
        stack <int> s;
        int ans = 0;
        while(i<n){
            while(s.empty() || height[i]<height[s.top()]){
                s.push(i++);
                if(i==n){
                    i--;
                    break ;
                }
            }
            while(!s.empty() && height[i]>height[s.top()]){
                int now = s.top();s.pop();
                if(s.empty()) break ;
                int d = i-s.top()-1;
                ans+=d*(min(height[i],height[s.top()])-height[now]);
            }
            s.push(i++);
        }
        return ans ;
    }
};

猜你喜欢

转载自www.cnblogs.com/heyuhhh/p/10226108.html