接雨水

原题链接

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

class Solution {
public:
    int trap(vector<int>& height) {
    int ans=0;
    int n=height.size();
    if(n<3)
        return 0;
    vector<int>max_left(n),max_right(n);
    max_left[0]=height[0],max_right[n-1]=height[n-1];
    //处理左边最值
    for(int i=1;i<n;i++)
        max_left[i]=max(height[i],max_left[i-1]);

    //处理右边最值
    for(int i=n-2;i>=0;i--)
        max_right[i]=max(height[i],max_right[i+1]);

    for(int i=1;i<n-1;i++)//舍弃两头
        ans+=min(max_left[i],max_right[i])-height[i];

    return ans;
    }
};
posted @ 2021-04-23 16:53  Tsukinousag1  阅读(81)  评论(0)    收藏  举报