給定 n 個非負整數表示每個寬度爲 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
上面是由數組 [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
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/trapping-rain-water
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
題解:
class Solution {
public int trap(int[] height) {
/**
每一個座標能接多少水 =取決於= min (它的左邊最高 和 右邊最高 的高度中的 min && 它自身的高度)
頭尾必然不儲存水:長度小於等於2的無法存水
*/
if(height.length <= 2){
return 0;
}
int len = height.length;
int[] left = new int[len];//每個結點左側當前最高
int[] right = new int[len];//每個結點右側當前最高
left[0] = height[0];
right[len-1] = height[len-1];//與left第一個結點 只作爲判斷索引,不計入最終總和
for(int i=1 ; i<len-1 ; i++){//左右數組同時遍歷
left[i] = height[i]>left[i-1]? height[i]:left[i-1];
int cur_right = len-1-i;//當前右側數組遍歷位置
right[cur_right] = height[cur_right]>right[cur_right+1]?height[cur_right]:right[cur_right+1];
}
int ret = 0;
for(int i=1 ; i<len-1 ; i++){
ret += (Math.min(left[i],right[i]) - height[i]);//左右最小的-當前高度
}
return ret;
}
}