I don't like to wait for others, and I don't like to be waited for by others.
Given n
a non-negative integer representing 1
the height map of each column with a width of , calculate how much rainwater the columns arranged in this way can catch after it rains.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above is composed of the array [0,1,0,2,1,0 ,1,3,2,1,2,1] represents the height map. In this case, 6 units of rainwater can be received (the blue part represents rainwater).
Example 2:
Input: height = [4,2,0,3,2,5] Output: 9
hint:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
Number of passes 773.8K Number of submissions 1.2M Pass rate 63.1%
The solution to the rainwater problem also adopts the double-pointer method
public int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int leftMax = 0;
int rightMax = 0;
int result = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
result += rightMax - height[right];
}
right--;
}
}
return result;
}