42 Trapping Rain Water

本文深入探讨了计算给定地形图中降雨后积水体积的问题,通过三种高效算法——双指针法、栈法及预计算左右最大值法,详细解析了如何在数组表示的地形中精确计算积水总量,为理解复杂数据结构与算法提供了实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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!

分析
  • 两个当前最高值中的较低值问题
方法
  • 从左边遍历,算出目前最高值,用vector保存,再从右边遍历,得到另一组目前最高值,比较两组最高值中的较低值,得到的最终vector就是积满雨水的数组。

  • 用两个指针从两边分别开始遍历,值小的指针向中间移动1(两个指针在最高值相遇,并停止遍历),如果该较小值,比下个数更大,就能乘雨水。

int trap(vector<int>& height) {
        int l = 0, r = height.size() - 1, level = 0, res = 0;
        while (l < r) {
            int lower = height[(height[l] < height[r]) ? l++ : r--];//两个高值中的较低值
            level = max(level, lower);//level:积满雨水后的高度
            res += level - lower;
        }
        return res;
    }
  • 使用栈(Stack),从0遍历,下坡则入栈,移位,上坡则出栈,计算,栈不为空继续计算,每次计算都把栈顶推出,栈为空则入栈,继续遍历。把栈顶元素取出来当作坑,新的栈顶元素就是左边界,当前高度是右边界,只要取二者较小的,减去坑的高度,长度就是右边界坐标减去左边界坐标再减1,二者相乘就是盛水量啦。
int trap(vector<int>& height) {
        stack<int> st;
        int i = 0, res = 0, n = height.size();
        while (i < n) {
            if (st.empty() || height[i] <= height[st.top()]) //
            {
                st.push(i++);
            } else {
                int t = st.top(); st.pop();
                if (st.empty()) continue;
                res += (min(height[i], height[st.top()]) - height[t]) * (i - st.top() - 1);
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值