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

每日温度 #398

Open
dossweet opened this issue Jan 17, 2023 · 0 comments
Open

每日温度 #398

dossweet opened this issue Jan 17, 2023 · 0 comments

Comments

@dossweet
Copy link
Contributor

来源:力扣第739题

题目描述:

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

解题思路:

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
let dailyTemperatures = function(temperatures){
    const n = temperatures.length;
    const res = Array(n).fill(0);
    const stack = [];  // 递增栈:用于存储元素右面第一个比他大的元素下标
    stack.push(0);
    for (let i = 1; i < n; i++) {
        while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
            const top = stack.pop();
            res[top] = i - top;
        }
        stack.push(i);
    }
    return res;
}
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

1 participant