leetcode 42.接雨水

假设雨水是从两面慢慢上涨的,左右两边那一边低先填充哪一边,达到最高之后雨水退去,留下的雨水就是所得

class Solution {
public:
    int trap(vector<int>& height) {
        int ret = 0 ;
        if(height.size()==0){
            return ret;
        }
        int l =0,r = height.size()-1;
        int lmax =0;
        int rmax = 0;
        while(l<r){
            lmax = max(lmax,height[l]);
            rmax = max(rmax,height[r]);
            if(lmax <= rmax){
                ret += lmax - height[l];
                l++;
            }else{
                ret += rmax - height[r];
                r--;

            }
        }
        return ret;
    }
};

你可能感兴趣的:(接雨水,leetcode)