挑战一下传说中的hard接雨水
木桶原理: 两片木板围成的区域能接住的水取决于较矮小的那片
height[i]
头上能接住的雨水等于height[i]
左边最高的悬崖峭壁和height[i]
右边最高的悬崖峭壁两者中较小的高度 减去 height[i]
height[i]
两侧最高的壁的高度甚至小于height[i]
,那么height[i]
头上接不住水/**
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
const len = height.length
let res = 0
const leftMax = new Array(len).fill(0)
const rightMax = new Array(len).fill(0)
let leftMaxHeight = 0
for (let i = 0; i < len; i++) {
leftMaxHeight = i ? Math.max(leftMaxHeight, height[i - 1]) : 0
leftMax[i] = leftMaxHeight
}
let rightMaxHeight = 0
for (let i = len - 1; i >= 0; i--) {
rightMaxHeight = i !== len - 1 ? Math.max(rightMaxHeight, height[i + 1]) : 0
rightMax[i] = rightMaxHeight
}
for (let i = 0; i < len; i++) {
const temp = Math.min(leftMax[i], rightMax[i]) - height[i]
res += Math.max(temp, 0)
}
return res
};
const height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
console.log(trap(height));
时间复杂度: O(3n) => O(n)
空间复杂度: O(2n + C) => O(n)