給定 n 個非負整數(shù)表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之后能接多少雨水。

image.png
上面是由數(shù)組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。 感謝 Marcos 貢獻此圖。
示例:
輸入: [0,1,0,2,1,0,1,3,2,1,2,1]
輸出: 6
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int left_max = 0, right_max = 0, ans = 0;
while (left < right) {
//左邊柱子的高度 < 右邊柱子,說明雨水是由左邊的柱子高度決定的,此時左指針前進,固定右指針
if (height[left] < height[right]) {
// 如果左邊柱子當(dāng)前柱子的高度小于左邊最高的柱子,說明出現(xiàn)了低洼,可以儲存雨水
if (height[left] < left_max) {
ans += left_max - height[left];
}else { //否則,說明左邊柱子當(dāng)前高度 >= left_max, 即沒有出現(xiàn)低洼,更新left_max
left_max = height[left];
}
left++;
}else {
if (height[right] < right_max) {
ans += right_max - height[right];
}else {
right_max = height[right];
}
right--;
}
}
return ans;
}