Leetcode---42. Trapping Rain Water

Source: Internet
Author: User

Title Link: 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.  ^ 3|              ■           □: water 2|      ■ □ □ □ ■ ■ □ ■     ■: elevation map 1|  ■ □ ■ ■ □ ■ ■ ■ ■ ■ ■  

The requirement of this problem is to calculate how much water can be loaded. Where the number in the array represents the height.

The idea of this problem is to use L and r two pointers to maintain the position on both sides of the water.

When the height of the L is low, the water on the right side is sure to be as high as L, at this time gradually right to move l, with the position of L and the right after the height difference (because it can be filled with water ah), until the same high or higher position. Then make the next round of judgment.

Similarly, when the height of R is low, the water on the left side of R must be as high as r, and then move the R to the left, with the difference between R and the left position, until the same high or higher position is encountered.

Finally until L and R meet, end.

Time complexity: O (N)

Space complexity: O (1)

1 class Solution2 {3  Public:4     int Trap(int A[], int N)5     {6         int Res = 0, L = 0, R = N - 1;7         8          while(L < R)9         {Ten             int Minh = min(A[L], A[R]); One             if(A[L] == Minh) A                  while(++ L < R && A[L] < Minh) -                     Res += Minh - A[L]; -             Else the                  while(L < -- R && A[R] < Minh) -                     Res += Minh - A[R]; -         } -          +         return Res; -     } + };

Reprint please indicate source: Leetcode---42. Trapping Rain Water

Leetcode---42. Trapping Rain Water

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.