【leetcode100】每日温度

1、题目描述

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

示例 1:

复制代码
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

复制代码
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

2、初始思路

2.1 思路

采用单调栈的方法及逆行优化,单调栈也就是(单调性+栈)。

2.1.1 从右到左

2.1.2 从左到右

3 完整代码

3.1.1 从右到左

复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        ans = [0] * n
        stack = []
        for i in range(n-1, -1, -1):
            while stack and temperatures[i] >= temperatures[stack[-1]]:
                stack.pop()
            if stack:
                ans[i] = stack[-1] - i
            stack.append(i)
        return ans

3.1.2 从左到右

复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        ans = [0] * n
        stack = []
        for i in range(n):
            while stack and temperatures[i] > temperatures[stack[-1]]:
                j = stack.pop()
                ans[j] = i - j
            stack.append(i)
        return ans
相关推荐
飞猪~2 小时前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319883 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_4 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
霸道流氓气质5 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗5 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
Frostnova丶5 小时前
(12)LeetCode 76. 最小覆盖子串
算法·leetcode·职场和发展
Metaphor6926 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
小七在进步6 小时前
数据结构:栈与队列之栈的实现
数据结构
言乐66 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle6 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding