Leetcode演算法Java全解答--42.接雨水
阿新 • • 發佈:2018-12-10
Leetcode演算法Java全解答–42.接雨水
文章目錄
題目
給定 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
想法
結果
// TODO
總結
// TODO
程式碼
我的答案
public class Solution { public int trap(int[] height) { int length; int maxLeftHeight = 0, maxRightHeight = 0; int result = 0; int temp; if (height == null || (length = height.length) == 0) return 0; int[] leftMaxHeight = new int[length]; int[] rightMaxHeight = new int[length]; for (int i = 0; i < length; i++) { leftMaxHeight[i] = maxLeftHeight; maxLeftHeight = Math.max(maxLeftHeight, height[i]); } for (int i = length - 1; i >= 0; i--) { rightMaxHeight[i] = maxRightHeight; maxRightHeight = Math.max(maxRightHeight, height[i]); } for (int i = 0; i < length; i++) { temp = Math.min(leftMaxHeight[i], rightMaxHeight[i]); if (temp >= height[i]) result += temp - height[i]; } return result; } }
大佬們的答案
測試用例
其他
程式碼託管碼雲地址:https://gitee.com/lizhaoandroid/LeetCodeAll.git
檢視其他內容可以點選專欄或者我的部落格哈:https://blog.csdn.net/cmqwan
“大佬們的答案” 標籤來自leetcode,侵權請聯絡我進行刪改
如有疑問請聯絡,聯絡方式:QQ3060507060