题目:
思路:
https://blog.csdn.net/weixin_45345143/article/details/128178541
代码:
public int trap(int[] height) {
int n = height.length;
int[] leftHeight = new int[n];
leftHeight[0] = height[0];
for (int i = 1; i < n; i++) {
leftHeight[i] = Math.max(leftHeight[i - 1], height[i]);
}
int[] rightHeight = new int[n];
rightHeight[n - 1] = height[n - 1];
for (int j = n - 2; j >= 0; j--) {
rightHeight[j] = Math.max(rightHeight[j + 1], height[j]);
}
int res = 0;
// 从左往右
for (int i = 0; i < n; i++) {
res += Math.min(leftHeight[i], rightHeight[i]) - height[i];
}
return res;
}