首页 > 代码库 > 42. Trapping Rain Water

42. 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], return 6.

技术分享

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!

 

此题和之前的container with most water有些类似,most water里面求的是装最多的水,且里面没有bar,而这道题里面水在哪个bar已经告诉我们了,并且中间由很多的bar,也是用two pointer来做,判定条件也几乎一样,看左右两边哪个bar小哪个进行移动,这里面需要设定两个maxleft,maxright变量,分别表示指针走过的额区域里面bar最大的高度,如果指针所到之处没有max大,则max-pointer为该指针所处位置的水深,否则(大于等于)max为指针所处bar的高度,代码如下:

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }</style> <style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545; min-height: 14.0px }</style>

public class Solution {

    public int trap(int[] height) {

        int left = 0;

        int right = height.length-1;

        int maxleft = 0;

        int maxright = 0;

        int sum = 0;

        while(left<right){

            if(height[left]<=height[right]){

                if(height[left]>=maxleft){

                    maxleft = height[left];

                }else{

                    sum+=maxleft-height[left];

                }

                left++;

            }else{

                if(height[right]>=maxright){

                     maxright = height[right];

                }else{

                    sum+=maxright-height[right];

                }

                right--;

            }

            

        }

        return sum;

    }

}

42. Trapping Rain Water