leetcode42 接雨水

 

 答案参考:https://www.zhihu.com/people/cxyxiaowu/activities

time O(n) space O(1):

双指针法,计算的中心思想为:

左右(包括自身)最低的柱子决定能装多少水,装水的体积为 water_i = min { l_max, r_max } - height[i];

然后结合双指针法进行计算,

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        int left=0;
        int right=n-1;
        int l_max=0;
        int r_max=0;
        int ans=0;
        while(left<right){
            l_max=max(l_max,height[left]);
            r_max=max(r_max,height[right]);
            if(l_max<r_max){
                ans+=l_max-height[left++];
            }else{
                ans+=r_max-height[right--];
            }
        }
        return ans;
    }
};

 

 

posted @ 2019-12-05 20:51  Joel_Wang  阅读(161)  评论(0编辑  收藏  举报