代码随想录算法训练营第57天|● 739. 每日温度 ● 496.下一个更大元素 I

单调栈:维持一个单调的栈,用于解决离最近的比自己大or小的元素的距离

739. 每日温度

和之前那个top k 最小堆感觉思路是一样的

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

496. 下一个更大元素 I

和上一题思路一样,实现上稍微绕了一下

python 复制代码
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res=[-1]*len(nums1)
        stack=[0]
        for i in range(1,len(nums2)):
            if nums2[i]<=nums2[stack[-1]]:
                stack.append(i)
            else:
                while stack and nums2[i]>nums2[stack[-1]]:
                    if nums2[stack[-1]] in nums1:
                        idx=nums1.index(nums2[stack[-1]])
                        res[idx]=nums2[i]
                    stack.pop()
                stack.append(i)
        return res
相关推荐
钱栈up36 分钟前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu38 分钟前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Agent世界1 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维
星夜离尘562 小时前
MATLAB:两路读数平均相差 8 mV,换位能分出传感器偏差和通道偏差吗?
开发语言·matlab
时间的情敌2 小时前
Three.js 水位模拟、水体 Shader、罐体液位动态变化(水箱、水池、储罐液位)
开发语言·javascript·three.js
Navigator_Z2 小时前
LeetCode //C - 1328. Break a Palindrome
c语言·算法·leetcode
电科_银尘2 小时前
【大模型算法与工程 46】vLLM部署入门:模型服务、请求与运行观测
算法·vllm
NendoZen2 小时前
Bubble Tea V2构建Go TUI应用教程
开发语言·golang·xcode
AskHarries2 小时前
社区运营打法
算法