LeetCode 题解: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.
在这里插入图片描述
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

解题思路

用一个栈记录遍历过的关键位置,将数组进行两次遍历即可得到答案。

  1. 第一次从左往右遍历数组:首先将下标0添加到栈中作为初始关键节点,然后从1开始遍历。当height[i] >= height[top] (其中top代表栈顶保存的下标位置)时,说明 i 和 top 之间存在空间能够存放雨水。此时对子区间(top, i)进行遍历,统计出这段子区间中的空白区。重复这一操作直到没有找到 满足 height[i] >= height[top] 的位置i。变量 rec 记录当前栈顶保存的位置 i。
  2. 第二次从右往左遍历数组:首先将下标height.size()-1添加到栈中作为初始关键节点,然后从height.size()-2开始遍历,到 rec 结束。当height[i] >= height[top] (其中top代表栈顶保存的下标位置)时,说明 i 和 top 之间存在空间能够存放雨水。此时对子区间 (i, top) 进行遍历,统计出这段子区间中的空白区。
  3. 将两次统计出的空白区间相加就得到最后的结果。

C++代码

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> pos;
        int sum = 0, rec = 0;
        pos.push(0);
        for(int i = 1; i < height.size(); i++) {
            if(height[i] >= height[pos.top()]) {
                for(int j = pos.top()+1; j < i; j++) {
                    sum += height[pos.top()] - height[j];
                }
                pos.push(i);
            }
        }
        rec = pos.top();
        pos.push(height.size()-1);
        for(int i = height.size()-2; i >= rec; i--) {
            if(height[i] >= height[pos.top()]) {
                for(int j = pos.top()-1; j > i; j--) {
                    sum += height[pos.top()] - height[j];
                }
                pos.push(i);
            }
        }
        
        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值