Trapping Rain Water

本文介绍了一个经典的算法问题——计算降雨后地图上能存储多少雨水。通过两次遍历找到每列左右最高点,进而计算出各位置能存储的水量。文章包含示例与详细解答。

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

Trapping Rain WaterMar 10 '12

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!


对于任意i,决定此列能装多少水的是它左边最大的高度和右边最大的高度。所以,先扫一遍可以得到每个i左边最高的高度值,然后从右向左扫一遍可以得到i右边最高的高度值,这次扫描时可以直接求出i的储水值,所以不再需要存储,直接通过这次扫描可以得到最后的返回值。


代码如下:

class Solution {
public:
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n <= 2) return 0;
        
        int* left_highest = new int[n];
        memset(left_highest,0,sizeof(int)*n);
        
        int left_max = 0;
        int right_max = 0;
        int sum = 0;
        
        for(int i = 0;i<n;i++)
        {
            left_highest[i] = left_max;
            left_max = max(left_max,A[i]);
        }
        
        for(int i = n-1; i >= 0; i--)
        {
            right_max = max(right_max,A[i]);
            sum += max(0,min(left_highest[i],right_max)-A[i]);
        }
        return sum;
    }
};

34 milli secs


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值