【LeetCode 算法笔记】739. 每日温度

目录

问题描述

给定一个整数数组 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]

示例 3:

输入: temperatures = [30,60,90]

输出: [1,1,0]

提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

暴力解法

对于每一个温度值,都向后进行扫描,直到找到比这个值更大的值。

python 复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        res = []
        n = len(temperatures)
        for i in range(n):
            j = 0
            finded = False
            while(i+j < n):
                if temperatures[i] < temperatures[i+j]:
                    finded = True
                    break
                else:
                    j += 1
            res.append(j if finded else 0)
        return res

算法复杂度:

最好的情况下,每一天的温度比前一天更高: O ( N ) O(N) O(N)

最坏情况下,每一天的温度比前一天更低,总共运行 N ∗ ( N − 1 ) / 2 N*(N-1)/2 N∗(N−1)/2 次 : O ( N 2 ) O(N^2) O(N2)

这个方法在 LeetCode 中提交的话,会超时无法通过

先把 下标存到栈里,如果栈顶元素遇到了更高的温度,持续抛出

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

算法复杂度: O ( N ) O(N) O(N)

相关推荐
!停15 小时前
数据结构二叉树——堆
java·数据结构·算法
AI营销前沿15 小时前
AI市场分析平台榜单发布:原圈科技如何破解全球化增长难题?
笔记
一匹电信狗1 天前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞1 天前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
三水不滴1 天前
Redis 过期删除与内存淘汰机制
数据库·经验分享·redis·笔记·后端·缓存
梵刹古音1 天前
【C语言】 函数基础与定义
c语言·开发语言·算法
筵陌1 天前
算法:模拟
算法
wdfk_prog1 天前
[Linux]学习笔记系列 -- [drivers][i2c]i2c-dev
linux·笔记·学习
土拨鼠烧电路1 天前
笔记03:业务语言速成:“人、货、场”模型与IT系统全景图
笔记
We་ct1 天前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript