【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
相关推荐
DFT计算杂谈14 小时前
VASP新手入门: IVDW 色散修正参数
linux·运维·服务器·python·算法
庚昀◟14 小时前
ClaudeCode安装教程,基础使用、进阶推荐
人工智能·python·ai
吃着火锅x唱着歌14 小时前
LeetCode 962.最大宽度坡
算法·leetcode·职场和发展
deephub15 小时前
告别脆弱的单体应用,用多智能体网络构建稳定的生产力工具
人工智能·python·大语言模型·多智能体
烟雨江南aabb15 小时前
Python第六弹:python爬虫篇:什么是爬虫
开发语言·爬虫·python
MomentYY15 小时前
第 1 篇:Agent 到底是什么?别被概念唬住了
人工智能·python·agent
无限进步_15 小时前
【C++】C++11的类功能增强与STL变化
java·前端·数据结构·c++·后端·算法
Python大数据分析@15 小时前
对你而言, Vibe Coding 的乐趣是什么?
python
WL_Aurora15 小时前
Python 算法基础篇之排序算法(一):冒泡、选择、插入
python·算法·排序算法
龙腾AI白云15 小时前
中国人工智能培训网—AI系列录播课
python·beautifulsoup