[LeetCode] 42. Trapping Rain Water

</br>


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.


</br>

Solution

This problem is kind of same as Histogram.
We first could determine the start point of the process of filling water. By implementing

while(l<r && height[l]<=height[l+1])  l++;
while(l<r && height[r]<=height[r-1])  r--;

we can move the pointer to the first bar where its volume is higher than its right one, otherwise the left side cannot keep the water from escaping. The same situation goes with the right side, then can save some overall time by avoiding unnecessary time to search from those impossible spot.

Then, from the start point, whenever there is a column lower than the left barricade, we can fill the water to level the gap; and if the left barricade is lower than the current column, it means this loop should be terminated and to find a new left barricade. The same situation goes with the right side.

Finally, dealing with the null situation by return 0 when the length of the array is shorter than 3, we should be good to go.

The code is shown as below.
Java

public class Solution {
    public int trap(int[] height) {
        
        if(height.length<3) return 0;
            
        int area = 0, l = 0, r = height.length-1;
        
        //Find the start pointer to avoid unnecessary calculation 
        while(l<r && height[l]<=height[l+1])  l++;
        while(l<r && height[r]<=height[r-1])  r--;
        
        while(l<r){
            int left = height[l], right = height[r];
            if (left <= right) {
            while (l < r && left >= height[++l]) 
                area += left - height[l];
            } else {
                while (l < r && height[--r] <= right) 
                    area += right - height[r];
            }
        }
        
        return area;
    }
}

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,921评论 0 23
  • 经常听到有人感叹:“早知道这个我就怎样怎样了……”,真的能够“早知道”的话,能获得他们所想象的结果么?一个孤立的“...
    LvJack阅读 188评论 0 0
  • 人与人之一个故事 说某天,上帝心血来潮种下一粒种子,精心呵护。种子发芽,成长,历经风雨,终于在上帝关照下长成了参天...
    仗剑客阅读 399评论 0 1
  • 1.我怎么如此幸运,想金姐了,就直接发微信,而不是想那么多的顾虑,直接了当就很好。 2.我怎么如此幸运,很想初中同...
    史真如阅读 113评论 0 0