給定 n 個非負整數表示每一個寬度爲 1 的柱子的高度圖,計算按此排列的柱子,下雨以後能接多少雨水。git
上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種狀況下,能夠接 6 個單位的雨水(藍色部分表示雨水)。github
示例:數組
輸入: [0,1,0,2,1,0,1,3,2,1,2,1] 輸出: 6
使用二分查找,找到最高的位置,今後處一分爲二,A左邊的從左往右遍歷,B右邊的從右往左遍歷,spa
A左邊:左邊>右邊, 左邊-右邊爲雨水量;blog
B右邊:右邊>左邊, 右邊-左邊爲雨水量;索引
加在一塊兒就是總量。get
public static int trap(int[] height) { int sum = 0;//雨水總數 int max = 0;//最大值 int maxIndex = 0;//最大值索引 for(int i =0 ;i< height.length; i++){ if (max < height[i]){ max = height[i]; maxIndex = i; } } int maxLeft = 0;//左邊最大 //遍歷左邊,從左往右遍歷 小於最大值索引 for (int a=0 ; a<maxIndex; a++){ int i = height[a]; //若是當前值大於等於左邊最大值 if (i >= maxLeft){ //將當前值賦值給左邊最大值 maxLeft = i; }else{ //若是當前值小於左邊最大值,左邊最大值減去當前值 sum+= maxLeft-i; } } int maxRight = 0;//右邊最大 //遍歷右邊,從右往左遍歷 小於最大值索引 for (int b = height.length-1; b > maxIndex; b--){ int j = height[b]; //若是當前值大於等於右邊最大值 if (j >= maxRight){ //將當前值賦值給左邊最大值 maxRight = j; }else{ //若是當前值小於右邊最大值,右邊最大值減去當前值 sum += maxRight - j; } } return sum; } public static void main(String[] args){ int[] height={0,1,0,2,1,0,1,3,2,1,2,1}; System.out.print(trap(height)); }
LeetCode 所有題目講解與答案,可移步 GitHub:https://github.com/yan-qiang/LeetCodeit