Trapping Rain Water
PreviousReverse Vowels of a String (easy)Next1498. Number of Subsequences That Satisfy the Given Sum Condition
Last updated
Last updated
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6// Updated: 09/26/2021
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = height[left];
int rightMax = height[right];
int water = 0;
while (left < right) {
if (leftMax > rightMax) {
// right位置的水量就是水面高度减去地面高度
water += rightMax - height[right];
right--;
rightMax = Math.max(rightMax, height[right]);
} else {
water += leftMax - height[left];
left++;
leftMax = Math.max(leftMax, height[left]);
}
}
return water;
}
}class Solution {
public int trap(int[] height) {
if (height.length == 0) return 0;
int[] leftMaxs = new int[height.length];
int[] rightMaxs = new int[height.length];
// 生成leftMax数组
leftMaxs[0] = height[0];
for (int i = 1; i < height.length; ++i) {
if (leftMaxs[i - 1] < height[i]) {
leftMaxs[i] = height[i];
} else {
leftMaxs[i] = leftMaxs[i - 1];
}
}
// 生成rightMax数组
rightMaxs[rightMaxs.length - 1] = height[height.length - 1];
for (int i = height.length - 2; i >= 0; --i) {
if (rightMaxs[i + 1] < height[i]) {
rightMaxs[i] = height[i];
} else {
rightMaxs[i] = rightMaxs[i + 1];
}
}
// 扫描height数组,累加每一条water
int water = 0;
for (int i = 0; i < height.length; ++i) {
int waterHeight = Math.min(leftMaxs[i], rightMaxs[i]);
if (waterHeight > height[i]) {
water += waterHeight - height[i];
}
}
return water;
}
}