[LeetCode]042-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!

Solution:
思路,先找到最高的点,然后两边处理。举例左边的情况:
设置两个指针i,j。i往中间最高点移动,若height[i] >=height[j]。则计算j和i之间的可存放空间,并将j移动到i的位置:j=i,i继续往后移动,直到最高点。右边的处理情况类似。
代码如下:

class Solution {
public:
    int trap(vector<int>& height)
    {
        int n = height.size();
        int i,j,k;
        int sum = 0;
        int h = 0;
        int max = 0;
        for(i =0;i<n;i++)
        {
            if(height[i] > max)
            {
                max = height[i];
                h = i;
            }
        }
        i = 0;
        j = i+1;
        while(i<=h && j <=h)
        {
            if(height[i] >=  height[j])
            {
                sum += calculate(height,j,i);
                j = i;
            }
            i++;
        }
        j=n-1;
        i = j-1;
        while(i >= h)
        {
            if(height[i] >=  height[j])
            {
                sum += calculate(height,i,j);
                j = i;
            }
            i--;
        }
        return sum;
    }
    int calculate(vector<int> height,int begin,int end)
    {
        int h = min(height[begin],height[end]);
        int w = end - begin-1;
        int area = h * w;
        for(int i = begin+1;i<end;i++)
        {
            area -= height[i];
        }

        return area<0?0:area;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值