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