【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
相关推荐
知远同学1 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
苏宸啊1 小时前
链式二叉树基操代码实现&OJ题目
数据结构
风筝在晴天搁浅1 小时前
hot100 25.K个一组翻转链表
数据结构·链表
Blossom.1181 小时前
AI编译器实战:从零手写算子融合与自动调度系统
人工智能·python·深度学习·机器学习·flask·transformer·tornado
小十一再加一2 小时前
【初阶数据结构】栈和队列
数据结构
热爱专研AI的学妹2 小时前
数眼搜索API与博查技术特性深度对比:实时性与数据完整性的核心差异
大数据·开发语言·数据库·人工智能·python
Mr_Chenph2 小时前
Miniconda3在Windows11上和本地Python共生
开发语言·python·miniconda3
长安er3 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
_w_z_j_3 小时前
最小栈(栈)
数据结构
fufu03114 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法