Skip to content

LeetCode 739. 每日温度 中等

作者:Choi Yang
更新于:4 个月前
字数统计:588 字
阅读时长:2 分钟
阅读量:

题目描述

请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/daily-temperatures 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

本题用到了单调栈的思路,将原本需要 O(n^2) 的时间复杂度降低到了 O(n)。

我们只需要维护一个新栈,首先遍历整个数组,只要栈不为空,如果当前的数字大于栈顶元素,则必定是第一个大于它的元素,我们只需要求出相差距离,然后存入结果就好了。

维护的新栈存放的是我们的元素下标,这样我们求距离时就很方便了,本题我觉得可以说是单调栈的一个模板题。专栏后续会有单调栈其它题目,可以查阅哈。

javascript
/**
 * @param {number[]} T
 * @return {number[]}
 */
var dailyTemperatures = function (T) {
  let stack = [];
  // 初始化气温列表,默认值为0
  let res = new Array(T.length).fill(0);
  for (let i = 0; i < T.length; i++) {
    //将栈顶元素下标对应的值和当前元素进行比较
    while (T[i] > T[stack[stack.length - 1]] && stack.length) {
      let idx = stack.pop();
      res[idx] = i - idx;
    }
    stack.push(i);
  }
  return res;
};
cpp
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        vector<int> res(T.size(), 0);
        stack<int> s;
        for (int i = 0; i < T.size(); i++) {
            while (!s.empty() && T[i] > T[s.top()]) {
                int idx = s.top();
                s.pop();
                res[idx] = i - idx;
            }
            s.push(i);
        }
        return res;
    }
};
java
class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] res = new int[T.length];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < T.length; i++) {
            while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
                int idx = stack.pop();
                res[idx] = i - idx;
            }
            stack.push(i);
        }
        return res;
    }
}
python
class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        res = [0] * len(T)
        stack = []
        for i in range(len(T)):
            while stack and T[i] > T[stack[-1]]:
                idx = stack.pop()
                res[idx] = i - idx
            stack.append(i)
        return res
javascript
学如逆水行舟,不进则退

Contributors

Choi Yang