代码随想录算法训练营第六十天 | 单调栈 part 1 | 739. 每日温度、496.下一个更大元素 I

本文介绍了LeetCode中的两个问题,分别是利用单调递增栈解决每日温度问题和使用栈与哈希表寻找下一个更大元素I。作者详细解释了两种算法的思路和Python代码实现,以及它们的时间复杂度和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

739. 每日温度

Leetcode

在这里插入图片描述

思路

维持一个单调递增的栈,向栈逐一pushtemperatures里的index。

  • 如果当前遍历的元素大于栈顶元素,这意味着 栈顶元素的 右边的最大的元素就是 当前遍历的元素,所以弹出 栈顶元素,并记录
  • 否则的话,可以直接入栈。

代码

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        stack = [0]
        answer = [0] * len(temperatures)

        for i in range(1, len(temperatures)):
            if temperatures[i] <= temperatures[stack[-1]]:
                stack.append(i)
            
            else:
                while len(stack) != 0 and temperatures[i] > temperatures[stack[-1]]:
                    answer[stack[-1]] = i - stack[-1]
                    stack.pop()
                stack.append(i)
        
        return answer
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

496.下一个更大元素 I

Leetcode

在这里插入图片描述

思路

这道题和上一题类似。

维护一个nums2的单调递增栈,只不过在pop的时候需要在nums1中寻找相应的index,这一步可以用.index(),也可以使用哈希表。

代码

.index()

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = [-1] * len(nums1)
        stack = [0]

        for i in range(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:
                        index = nums1.index(nums2[stack[-1]])
                        res[index] = nums2[i]
                    stack.pop()
                stack.append(i)
        
        return res

哈希表

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = [-1] * len(nums1)
        stack = [0]
        dic = {}
        for i, v in enumerate(nums1):
            dic[v] = i
        for i in range(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:
                        index = dic[nums2[stack[-1]]]
                        res[index] = nums2[i]
                    stack.pop()
                stack.append(i)
        
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值