单调栈_ 739_每日温度

文章目录

题目描述

在这里插入图片描述

思路

  • 单调栈 - 栈中存放数组元素的下标
class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        stack = []
        res = [0] * len(T)
        for i in range(len(T)):
            if not stack or T[i] <= T[stack[-1]]:  # 栈空 或 T[i]小于栈顶元素
                stack.append(i)
            else:
                while stack and T[i]>T[stack[-1]]:
                    top = stack.pop()
                    res[top] = i-top
                stack.append(i)
        return res
  • 复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n是温度列表的长度。正向遍历温度列表一遍,对于温度列表中的每个下标,最多有一次进栈和出栈的操作。

  • 空间复杂度: O ( n ) O(n) O(n),其中 n是温度列表的长度。需要维护一个单调栈存储温度列表中的下标。

猜你喜欢

转载自blog.csdn.net/m0_38024592/article/details/106678885