Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

接雨水 #363

Open
lzxjack opened this issue Jan 11, 2023 · 2 comments
Open

接雨水 #363

lzxjack opened this issue Jan 11, 2023 · 2 comments

Comments

@lzxjack
Copy link
Contributor

lzxjack commented Jan 11, 2023

No description provided.

@dossweet
Copy link
Contributor

题目描述

给定 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;
};

@Pcjmy
Copy link
Contributor

Pcjmy commented Mar 2, 2023

题目链接: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;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants