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.


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

这道题我采用的方法是把这个模型看成一层一层的水池,每次计算一层容量。以第一层为例,找到第一层左壁(第一个不为零的数),然后用 l 标记,从 l+1 的位置开始,向右寻找,找到右壁,计算中间的空间,然后右壁变左壁,继续向右寻找。找完第一层,再找第二层,依次到最高层。

 

代码如下:

class Solution {
public:
    int trap(vector<int>& height) {
        int highest = 0 ;
        int count = 0 ;

        for( auto i:height ){
        	if( i> highest ){
        		highest = i ;
        	}
        }

        for( int i=1;i<=highest;i++ ){
        	int l = 0 ;
            int r ;

        	for( int j=0;j<height.size();j++ ){
        		if( height[j]>=i ){
        			l = j ;
        			r = l ;
                    break ;
        		}
        	}

        	for( int j=l+1;j<height.size(); ){
        		if( height[j]>=i ){
        			r = j ;
        			count += (r-l-1) ;
        			l = r ;
        			j = l+1 ;
        		}
        		else{
        			j++ ;
        		}
        	}
        }

        return count ;

    }
};

 

 

在讨论去看到一个高分答案,觉得思路惊奇。先贴代码:

class Solution {
public:
    int trap(vector<int>& height) {
        int i=0,j=height.size()-1;
        int lmax=0, rmax = 0;

        int container = 0;

        while(i<j){
            lmax = height[i] > lmax? height[i]:lmax;
            rmax = height[j] > rmax? height[j]:rmax;

            if(lmax < rmax){
                container += lmax - height[i];
                i++;
            }else{
                container += rmax - height[j];
                j--;
            }
        }
        
        return container;
    }
};

他的思路是:

在水池左右两边设立两个标杆,记录左右两边的最高高度,以所给例子为例,一开始左右两边高度为0 ,那么说明左边标杆右边低于一的区域都会有水。标杆每次向中间推进一格,先更新标杆的高度,再判断当前格子中有多少水,用最高高度减去当前格子的高度就可以得到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值