42.蓄水池问题

Trapping Rain Water

问题描述:

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
蓄水池

测试代码:

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

性能:

这里写图片描述

参考答案:

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.size() < 3)
            return 0;

        int left = 0;
        int leftMax = 0;    //local max value from left
        int right = height.size() - 1;
        int rightMax = 0;    //local max value from right
        int result = 0;    //result is an accumulation value. add value to it during each loop, which means we don't calculate it
                           //directly, we calculate it at each point. the gap between local max and height at that point is the 
        while(left < right)//capacity at that point. we add it to result, so the total result is the final result. and only if 
        {                  //left can meet right, we have scaned all the points. and using two pointers can avoid wrong results
                           //in triangle arrays, such as[1,2,3,4,3,2,1].
            leftMax = max(leftMax, height[left]);    //get the local max value at current heights
            rightMax = max(rightMax, height[right]);

            if(height[left] < height[right])    //if height[left] < height[right] means we shoud move the left
            {
                result += leftMax - height[left];    //add the gap between leftMax and height[left], it is the water capacity at
                ++left;                              //this point.
            }
            else
            {
                result += rightMax - height[right];
                --right;
            }
        }
        return result;
    }
};

性能:

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值