【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
相关推荐
天若有情6732 小时前
【python】Python爬虫入门教程:使用requests库
开发语言·爬虫·python·网络爬虫·request
IT北辰2 小时前
用Python+MySQL实战解锁企业财务数据分析
python·mysql·数据分析
Lucky高2 小时前
selenium(WEB自动化工具)
python
秃然想通2 小时前
掌握Python三大语句:顺序、条件与循环
开发语言·python·numpy
小学生的信奥之路3 小时前
力扣1116题:用C++实现多线程交替输出零、偶数、奇数
c++·leetcode·多线程
骇客野人3 小时前
使用python写一套完整的智能体小程序
开发语言·python
山楂树の4 小时前
模型优化——在MacOS 上使用 Python 脚本批量大幅度精简 GLB 模型(通过 Blender 处理)
python·macos·3d·图形渲染·blender
玄月初二丶4 小时前
28. 找出字符串中第一个匹配项的下标
c语言·开发语言·数据结构·算法
云霄IT4 小时前
python之使用ffmpeg下载直播推流视频rtmp、m3u8协议实时获取时间进度
python·ffmpeg·音视频
沐风清扬5 小时前
Win10下python环境变量呼出微软应用商店
开发语言·python