题解:Trapping Rain Water

本文介绍了一种计算给定地形图中雨后积水总量的方法。通过双指针技术从前向后遍历地形高度数组,根据左右两侧最高点确定积水容量,最终得出积水总量。

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

题目如下:

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!

解题方面,从前到后遍历,判断左右高度后累增水的数量,这个数量应该要是较低一边的数量(较高的减去较小的),并且坐标有相应的增大/减小。设置的两个坐标一个从最左边开始一个从最右边开始,依据前面的规则向中间靠拢。当左边坐标不再小于右边完成。代码如下:

int trap(vector<int>& height) {
	int result = 0;
    int i = 0, k = height.size() - 1;
    int h;
    while (i < k) {
        if (height[i] < height[k]) {
            h = height[i++];
            while (i < k && height[i] <= h) {
                result += h - height[i];
                i++;
            }
        }
		else {
            h = height[k--];
            while (i < k && height[k] <= h) {
                result += h - height[k];
                k--;
            }
        }
    }
    return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值