代码随想录算法训练营第五十八天| 第十章 单调栈:739.每日温度,496.下一个更大元素I(python)

目录

739.每日温度

496.下一个更大元素I


 

739.每日温度

文字讲解链接

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        res = [0]*n
        stack = [0]
        for i in range(1, n):
            # 情况一和情况二
            if temperatures[i] <= temperatures[stack[-1]]:
                stack.append(i)
            # 情况三
            else:
                while len(stack) != 0 and temperatures[i] > temperatures[stack[-1]]:
                    res[stack[-1]]=i-stack[-1]
                    stack.pop()
                stack.append(i)
        return res

496.下一个更大元素I

文字讲解链接

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 len(stack)!=0 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

你可能感兴趣的:(leetcode,算法,python)