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

739. 每日温度 

代码随想录

class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        #set up result
        result=[0]*len(temperatures)
        #set up stack, and put the first index
        stack=[0]
        # forloop from 1 to the end
        for i in range(1,len(temperatures)):
            #if current temperature is smaller than the last temperature in stack
            if temperatures[i]<=temperatures[stack[-1]]:
            #just append i to stack 
                stack.append(i)
            #if current temperature is larger than the last temperature in stack
            else:
                #while loop only when stack is not empty or 
                #current temperature is larger than the last temperature in stack
                while len(stack)!=0 and temperatures[i]>temperatures[stack[-1]]:
                    #record result
                    result[stack[-1]]=i-stack[-1]
                    #pop last element in stack 
                    stack.pop()
                stack.append(i)
        return result

496.下一个更大元素 I 

代码随想录

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        #set up result, a list of -1, which means no match
        result=[-1]*len(nums1)
        #set up stack
        stack=[0]
        #loop from 1 
        for i in range(1,len(nums2)):
            #if current nums value is smaller or equal to the smallest value 
            #recorded in stack
            if nums2[i]<=nums2[stack[-1]]:
                #append i to stack
                stack.append(i)
            #if current nums value is greater the smallest value 
            #recorded in stack
            else:
                #loop when stack is not empty and the current nums value 
                #is greater the smallest value recorded in stack
                while len(stack)!=0 and nums2[i]>nums2[stack[-1]]:
                    #if current smallest value recorded in stack is in nums1
                    if nums2[stack[-1]] in nums1:
                        #update result
                        result[nums1.index(nums2[stack[-1]])]=nums2[i]
                    #pop usded stack element
                    stack.pop()
                #append new i
                stack.append(i)
        return result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值