[Leetcode] 42. Trapping Rain Water_hard Tag:two pointers

Source: Internet
Author: User

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.


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.

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]output:6

This topic is similar to the barrel principle, the middle can collect the water, depending on the left and right sides of the shorter height, and then go to the middle, until the two meet. So set L, R, LH (left height), rh (right height), Judge L,r point to building
That short move which, for example L refers to the shorter, then l+= 1, then if the new building than the corresponding left height to short, ans + = left height-building[l], otherwise height = building[l], if R refers to a shorter, then
The situation is similar.

1. Constraints
1) empty, Edge case, return 0
2) element would be >= 0 integer

2. Ideas

Points: t:o (n) s:o (1)

3. Code
classSolution:defTraprainwater (self, heights):if  notHeightsreturn0 L, R, ans= 0, Len (Heights)-1, 0 LH, RH=Heights[l], Heights[r] whileL <r:ifHEIGHTS[L] <=Heights[r]: l+ = 1ifHEIGHTS[L] <Lh:ans+ = LH-Heights[l]Else: LH=Heights[l]Else: R-= 1ifHEIGHTS[R] <Rh:ans+ = RH-Heights[r]Else: RH=Heights[r]returnAns

4. Test Cases

1) Empty

2) 1, 2, 3

3)

[0,1,0,2,1,0,1,3]

[Leetcode] 42. Trapping Rain Water_hard tag:two pointers

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.