Closed rottenpen closed 3 years ago
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
let max = Math.max(...height)
// let maxIndexs = []
let l = 0
let r = height.length - 1
let sum = 0
let maxIndex = height.indexOf(max)
let lastLeft = 0
let lastRight = 0
// console.log(maxIndex)
if(!height.length){
return 0
} else {
while (l<r) {
if(l !== maxIndex) {
let ll = l ? height[l - 1] : 0
lastLeft = lastLeft < ll ? ll: lastLeft
let diffLeft = lastLeft - height[l] // 左边高于下一个
// console.log("l" + ll, lastLeft, diffLeft)
sum = diffLeft > 0 ? sum + diffLeft : sum
l ++;
}
if(r !== maxIndex) {
let rr = r < height.length - 1 ? height[r + 1] : 0
lastRight = lastRight < rr ? rr: lastRight
let diffRight = lastRight - height[r] // 左边高于下一个
// console.log("r" + rr,r, lastRight, diffRight)
sum = diffRight > 0 ? sum + diffRight : sum
r --;
}
}
}
return sum
};
终于成了
失败方案1:
失败方案2: