leetcode 42 Trapping Rain Water

DescriptionHintsSubmissionsDiscussSolution
Discuss Pick One
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:
    typedef vector<int>::size_type sz;

    int trap(vector<int>& height) {
        sz size = height.size();
        if (size <= 2) return 0;

        int ret = 0; // how many units of rain water trapped

        // the max left height
        sz max_lo;
        if (height[0] > height[1])
            max_lo = 0;
        else
            max_lo = 1;

        for (sz i = 2; i < size; ++i) {

            // 当height[i] > height[i - 1] 时才可以蓄水
            if (height[i - 1] < height[i]) { 
                int base = height[i - 1];

                // for 循环是因为 height[i] 可能与多栏蓄水如 【4 2 0 3】
                // 当 j 小于 max_lo 时说明左边没有更高的栏所以不用计算
                for (int j = i - 2; j >= int(max_lo); --j){
                    int h = 0;

                    // 当 height[j] > base 时说明该栏与height[i] 之间可以蓄水
                    if (height[j] > base) {
                        h = min(height[j], height[i]);  
                        ret += (i - j  - 1) * (h - base);
                        base = h;
                    }
                    if (height[j] >= height[i])
                        break;
                }

                if (height[i] >= height[max_lo]) {
                    max_lo = i;
                } 
            }
        }
        return ret;  
    }
};

参考后

class Solution {
public:
    typedef vector<int>::size_type sz;

    int trap(vector<int>& height) {
        sz size = height.size();
        if (size == 0) return 0;
        sz lo = 0;
        sz hi = size - 1;

        int ret = 0;

        while (lo < hi) {

            while (height[lo] <= height[hi]) {
                sz i = lo + 1; 
                while (height[i] < height[lo]) {
                    ret += height[lo] - height[i];
                    cout << ret << "i" << endl;
                    ++i;
                }
                lo = i;
                if (lo == hi) return ret;
            }

            while (height[lo] > height[hi]) {
                sz i = hi - 1;
                while (height[i] < height[hi]) {
                    ret += height[hi] - height[i];
                    --i;
                }
                hi = i;
                if (lo == hi) return ret;
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值