[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], return6.

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!

题意:求所有能收集到的雨水

思路:

代码如下:

 1 class Solution {
 2 public:
 3     int trap(int A[], int n) 
 4     {
 5         int maxIdx=0;
 6         for(int i=0;i<n;++i)
 7         {
 8             if(A[i]>A[maxIdx])
 9                 maxIdx=i;
10         }
11 
12         int left=0,right=0;
13         int sum=0;
14         for(int i=0;i<maxIdx;++i)   //计算左边容量
15         {
16             if(left>A[i])
17                 sum+=left-A[i];
18             else
19                 left=A[i];
20         }
21         for(int i=n-1;i>maxIdx;i--)     //加上右边容量
22         {
23             if(right>A[i])
24                 sum+=right-A[i];
25             else
26                 right=A[i];
27         }
28 
29         return sum;    
30     }
31 };

方法二:这题和最大水容器有点类似。定义两个指针,分别指向数组的两端,然后从两边向中间变历。具体思路:取两端中值较小(lower)的那段开始向中间遍历,若下一比lower小,则sum加上两者差值就行,left++,对应的值再和lower比较,若还是小于则继续加上差值,若不小于了,则将该值重新和right对应的值比较,重新确定lower值。重复上述过程。这里要注意的是:若连续是左端(右端)为较小值那端,Lower应该是固定的,直到条件不满足。代码如下:

 1 class Solution {
 2 public:
 3     int trap(int A[], int n) 
 4     {
 5         int left=0,right=n-1;
 6         int sum=0;
 7 
 8         while(left<right)
 9         {
10             int lower=min(left,right);
11             if(A[left]<A[right])
12             {
13                 left++;
14                 while(left<right&&A[left]<lower)
15                     sum+=A[lower]-A[left];
16             }
17             else
18             {
19                 right--;
20                 while(left<right&&A[right]<lower)
21                     sum+=A[lower]-A[right];
22             }
23         }
24         return sum;
25     }
26 };

 

转载于:https://www.cnblogs.com/love-yh/p/7191029.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值