← 中文资源

简体中文版本

单调栈找下一个更大元素

栈里只留尚未等到更大值的下标,且值自底向顶递减;遇到更大值就一次性结算所有等待者,线性一趟替代逐个向右扫描,每个下标只进出栈一次。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

prices : [4, 8, 5, 2, 9, 6]
greater: [8, 9, 9, 9, -1, -1]
temps  : [73, 74, 75, 71, 69, 72]
greater: [74, 75, -1, 72, 72, -1]

实现说明

逻辑集中在函数 next_greater里。 for i, value in enumerate(values) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 演示输出是带标签的(prices :、greater:),每个操作都会留下自己的一行标注。
  • 值得导入的表面是 next_greater;周围的辅助代码对片段是私有的。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 next_greater。

签名一览:def next_greater(values)

代码示例

def next_greater(values):
    """For each index, the next value to its right that is strictly larger."""
    result = [-1] * len(values)
    # The stack stays monotonic: indices whose values still decrease.
    stack = []
    for i, value in enumerate(values):
        # A bigger value resolves every smaller value waiting on the stack.
        while stack and values[stack[-1]] < value:
            result[stack.pop()] = value
        stack.append(i)
    return result

prices = [4, 8, 5, 2, 9, 6]
print("prices :", prices)
print("greater:", next_greater(prices))

temps = [73, 74, 75, 71, 69, 72]
print("temps  :", temps)
print("greater:", next_greater(temps))