leetcode-42. 接雨水

 

 

解析参见:

https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/327718/

class Solution {
public:
    int trap(vector<int>& height) {
        int left = 0;
        int right = height.size()-1;
        int left_max = 0;
        int right_max = 0;
        int res = 0;
        while(left<=right){
        //如果left_max<right_max成立,那么它就知道自己能存多少水了。
        //无论右边将来会不会出现更大的right_max。

        // 存水取决于较小的一方,所以left_max < right_max时,从左边开始算
            if(left_max < right_max){
                int tmp = max(0,(left_max-height[left]));
                left_max = max(left_max,height[left]);
                res = res + tmp;
                left++;
            }else{
                int tmp = max(0,(right_max-height[right]));
                right_max = max(right_max,height[right]);
                res = res + tmp;
                right--;
            }

        }
        return res;
    }
};

 

posted @ 2021-07-16 16:04  三一一一317  阅读(38)  评论(0)    收藏  举报