[Leetcode] Trapping Rain Water

Source: Internet
Author: User

Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the 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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!

Algorithm ideas:

The short plate effect, the tank is related to the short plate. Find the longest plate in the height array, then iterate from both ends to the long plate, meet the shorter to find the amount of the shelf, and meet the longer, then update the edge.

The code is as follows:

1  Public classSolution {2      Public intTrapint[] height) {3         if(Height = =NULL|| Height.length <3)return 0;4         intMax =0;5          for(inti =0; I < height.length;i++){6             if(Height[i] > Height[max]) max =i;7         }8         intHigh =0, res =0;9          for(inti =0; i < Max; i++){Ten             if(Height[i] <Height[high]) { OneRes + = Height[high]-Height[i]; A}Else if(Height[i] >Height[high]) { -High =i; -             } the         } -High = Height.length-1; -          for(inti = height.length-1; i > Max; i--){ -             if(Height[i] <Height[high]) { +Res + = Height[high]-Height[i]; -}Else if(Height[i] >Height[high]) { +High =i; A             } at         } -         returnRes; -     } -}

Specific algorithm analysis can be referred to here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.