码迷,mamicode.com
首页 > 移动开发 > 详细

LeetCode第[42]题(Java):Trapping Rain Water

时间:2018-05-08 00:52:22      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:col   images   lse   har   技术分享   mos   HERE   example   tle   

题目:接雨水

难度: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]; 

 

LeetCode第[42]题(Java):Trapping Rain Water

标签:col   images   lse   har   技术分享   mos   HERE   example   tle   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!