实现说明
逻辑集中在函数 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))