接雨水
lzxjack opened this issue · comments
题目描述
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例代码
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
const n = height.length;
if (n === 0){
return 0;
}
const leftMax = new Array(n).fill(0);
leftMax[0] = height[0];
for (let i = 1; i < n; i++){
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
const rightMax = new Array(n).fill(0);
rightMax[n - 1] = height[n - 1];
for (let i = n - 2; i >= 0; i--){
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
let sum = 0;
for (let i = 0; i < n; i++){
sum += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return sum;
};
题目链接:https://leetcode.cn/problems/trapping-rain-water/description
时间复杂度:O(n)
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
let len=height.length;
let left=new Array(len);
let right=new Array(len);
left[0]=height[0];
for(let i=1;i<len;i++)
{
left[i]=Math.max(height[i],left[i-1]);
}
right[len-1]=height[len-1];
for(let i=len-2;i>=0;i--)
{
right[i]=Math.max(height[i],right[i+1]);
}
let ans=0;
for(let i=1;i<len-1;i++)
{
let mn=Math.min(left[i-1],right[i+1]);
ans+=Math.max(mn-height[i],0);
}
return ans;
};