Leetcode:trapping Rain Water Problem Solving report

Source: Internet
Author: User

https://oj.leetcode.com/problems/trapping-rain-water/

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

Solution 1:

Scan from left to right, calculate to the highest bar from left to Curr, scan right to left, calculate to the highest bar from right to Curr.

Scan again, the lower of the two as the height of the {barrel}, if the barrel is higher than a[i] bar, then a[i] This bar can store height-a[i] so much water. Add up all the water.

1  Public classSolution {2      Public intTrapint[] A) {3         if(A = =NULL) {4             return 0;5         }6         7         intMax =0;8         9         intLen =a.length;Ten         int[] left =New int[Len]; One         int[] right =New int[Len]; A          -         //count the highest bar from the left to the current. -          for(inti =0; i < Len; i++) { theLeft[i] = i = =0? A[i]: Math.max (Left[i-1], a[i]); -         } -          -         //count the highest bar from right to current. +          for(inti = len-1; I >=0; i--) { -Right[i] = i = = Len-1? A[i]: Math.max (right[i +1], a[i]); +         } A          at         //count the largest water which can contain. -          for(inti =0; i < Len; i++) { -             intHeight =math.min (Right[i], left[i]); -             if(Height >A[i]) { -Max + = height-A[i]; -             } in         } -          to         returnMax; +     } -}
View Code

CODE:

Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/Trap.java

Leetcode:trapping Rain Water Problem Solving report

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.