LeetCode题解——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!

这道题和container with most water 有点类似,但是这道题更难一点;分析题目可看出,随意给定一组数字,可能形成很多个"坑",那么是否可以每次计算出一个坑中的水,最后将其相加得到最终结果。

用递归是容易做到的,每次找出两个最高的bar,然后计算这两个bar之间的水量,再分别在其左边和右边递归的进行寻找。

class Solution {
public:
    int trap(vector<int>& height) {//用递归可以实现
        
        if(height.size()<3) return 0;
        
		int maxidxI=0,maxidxJ=height.size()-1;
        int temp,water = 0;

		for(int i=1;i<height.size()-1;i++)
		{
			if(height[i]>height[maxidxI])
				maxidxI = i;
		}
		for(int i =height.size()-1;i>=0;i--)
		{
		    if(height[i]>height[maxidxJ] && i!=maxidxI)
		        maxidxJ = i;
		}

		if(maxidxI>maxidxJ)
		{
			int t = maxidxI;
			maxidxI =maxidxJ;
			maxidxJ =t;
		}

        temp =0;
        for(int m = maxidxI+1 ; m<= maxidxJ-1; m++)
            temp+= height[m];
        water+=(height[maxidxI]>height[maxidxJ]?height[maxidxJ]:height[maxidxI])*(maxidxJ - maxidxI -1) - temp;
        vector<int> l(height.begin(),height.begin()+maxidxI+1),r(height.begin()+maxidxJ,height.end());
        
        return water+trap(l)+trap(r);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值