思路:一块柱子能接水的量取决于它左右两边最高的柱子中较短的一个。
class Solution {
public int trap(int[] height) {
int left[] = new int[height.length];
int right[] = new int[height.length];
int max = 0;
for (int i = 0; i < height.length; i++) {
max = Math.max(max, height[i]);
left[i] = max;
}
max = 0;
for (int i = height.length - 1; i >= 0; i--) {
max = Math.max(max, height[i]);
right[i] = max;
}
int ans = 0;
for (int k = 1; k < height.length - 1; k++) {
if (left[k - 1] <= 0 || right[k + 1] <= 0) continue;
int tmp = Math.min(left[k - 1], right[k + 1]) - height[k];
if (tmp > 0) ans += tmp;
}
return ans;
}
}
原文地址:https://www.cnblogs.com/acbingo/p/9339010.html
时间: 2024-10-16 10:58:24