Leetcode 42.接雨水

接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]

输出: 6

这道题立马让我想到了之前做过的一道求两条柱子间面积的题。此题使用了类似的方法。我们不用仔细地计算每个"容器的装水"容量、我们只需要计算装水前的容器面积和装满水后的容器面积之差即可。此题的难点是如何装满水成为一个新nums。在此我使用了从头和尾夹逼的方法,从低往高装水。装完一层形成新的数组再装下一层~

 1 public class Solution {
 2     public int trap(int[] height) {
 3         int preS=0;    //原面积
 4         int aftS=0;    //后面积
 5         int pre=0;
 6         int aft=height.length-1;
 7         int temp;
 8         for(int i=0;i<height.length;i++){
 9             preS+=height[i];
10         }
11         while(pre<aft){
12             if(height[pre]<height[aft]){
13                 temp=height[pre];
14             }else{
15                 temp=height[aft];
16             }
17             for(int j=pre+1;j<aft;j++){
18                 height[j]=Math.max(temp, height[j]);
19             }
20             if(height[pre]<height[aft]){
21                 while(pre<aft&&height[pre]<=temp){
22                     pre++;
23                 }
24             }else{
25                 while(aft>pre&&height[aft]<=temp){
26                     aft--;
27                 }
28             }
29         }
30         for(int i=0;i<height.length;i++){
31             aftS+=height[i];
32         }
33         return aftS-preS;
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10163023.html