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
文章介绍了两个使用栈数据结构解决的编程问题:一是计算每日温度中比当前日更高的温度需要等待的天数;二是找出数组中的下一个更大元素。解决方案都涉及到栈的压入和弹出操作,以及比较元素大小来更新结果。
1173

被折叠的 条评论
为什么被折叠?



