LeetCode第[42]题(Java):Trapping Rain Water (数组方块盛水)——HARD

题目:接雨水

难度:hard

题目内容

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.


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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

翻译:简单翻译下就是,给出每一格木块的数量,最后求得这些木块放在一起时能接住多少雨水。

我的思路:此题和第11题很像:Container With Most Water,但是11题里是竖线,这里是方块,而且那是寻求所接水最多的,这里是求所能接住的所有水,不过取水的思想可以参考一下,就是利用双指针,同向移动。每次移动两边比较矮的那一个。

     然而,因为考虑到要减去方体的体积,我还是不会做这个。

 

答案代码

 1     public int trap(int[] height) {
 2         if (height.length == 0) return 0;
 3         int left = 0;
 4         int right = height.length - 1;
 5         int area = 0, leftHeight = height[0], rightHeight = height[height.length - 1];
 6         while (left < right){
 7             if (height[left] < height[right]){
 8                 left++;
 9                 leftHeight = Math.max(leftHeight, height[left]);
10                 area += leftHeight - height[left];
11             }
12             else{
13                 right--;
14                 rightHeight = Math.max(rightHeight, height[right]);
15                 area += rightHeight - height[right];
16             }
17         }
18         return area;
19     }

答案复杂度:O(N)

答案思路:果然,是利用了双指针,每次移动比较矮的那一边。

然后,重点来了!

如果移动后的当前高度比移动的这一方的最高的高度要矮,那么储水的量就要加上他们之间的这个差值

举个例子:(以【】代替方块,___代表0个方块)

【】

【】             【】

【】_________【】【】

  A        B    C

首先因为A比C高,所以移动C那边的指针right,right移动到B点,然后取 high[right]  (B)与 之前的最高高度 C 比较,得到还是C高,而因为这边是矮的迟早对面会比这个高,所以此时储水量就应该加上(C-B)。【每移动一格储水量加上移动的这一格能接的水

而如果当前移动后就是最高的高度,那么储水量则不增加。

所以最后每次移动后,储水量应该加上   ( 此方向的最高高度  -   当前高度 ),对应代码: area += leftHeight - height[left]; 

本题代码结构和11题Container With Most Water还是有些区别:

1. 多了两边的最高高度记录(eg.rightHeight);

2.本题是先比较左右高矮,移动之后再计算移动产生的盛水量,11题是每次先计算了当前总盛水量再比较看移动那一边。

原文地址:https://www.cnblogs.com/Xieyang-blog/p/9005898.html