42. 接雨水

#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
    int trap(vector<int>& height) {
        int len=height.size();
        //当前位置左边界最大值
        int left[len];
        //当前位置右边界最大值
        int right[len];
        left[0]=height[0];
        right[len-1]=height[len-1];
        int res=0;
        for (int i = 1; i < len; i++)
        {
            left[i]=max(left[i-1],height[i]);
            right[len-1-i]=max(right[len-i],height[len-1-i]);
        }
        //左右边界最小值与当前位置高度的差,即为当前可存储的雨水
        for (int i = 0; i < len; i++)
        {
            int temp=min(left[i],right[i]);
            if (temp-height[i]>0)
            {
                res+=temp-height[i];
            }
            
        }
        return res;
    }
};
int main(){
    Solution s;
    vector<int> height={0,1,0,2,1,0,1,3,2,1,2,1};
    cout<<s.trap(height);
    return 0;
}

 

posted on 2022-12-05 21:36  一仟零一夜丶  阅读(66)  评论(0)    收藏  举报