LeetCode --- 42. Trapping Rain Water
Link: Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 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 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 rain water (blue section) are being trapped.
The requirement for this question is to calculate the maximum amount of water that can be loaded. The numbers in the array indicate the height.
The idea of this question is to use two pointers, l and r, to maintain the positions on both sides of the water.
When the height of l is low, it indicates that the water on the right side of l must be as high as that of l. At this time, l is gradually shifted to the right, in the same way, the height difference between the l position and the right position is added (because water can be filled here) until the same height or higher position is reached. Then proceed to the next round of judgment.
Similarly, when the height of r is low, it indicates that the water on the left side of r must be as high as that on the r side. At this time, the r is gradually shifted to the left, and the height difference between the r and the left-shift position is added, until the system encounters a position of the same height or higher.
Finally, it is not until l and r meet and end.
Time Complexity: O (n)
Space complexity: O (1)
1 class Solution 2 { 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 {10 int minh = min(A[l], A[r]);11 if(A[l] == minh)12 while(++ l < r && A[l] < minh)13 res += minh - A[l];14 else15 while(l < -- r && A[r] < minh)16 res += minh - A[r];17 }18 19 return res;20 }21 };