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