1. 739. 每日温度
单调栈通常使用在:一维数组,要寻找任一元素的右边或者左边第一个比自己大或者小的元素的位置,时间复杂度为 O ( n ) O(n) O(n)。单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是整个数组只需要遍历一次。在本题中,需要寻找右边第一个比自己大的元素,从栈头到栈底是递增的顺序,这样要加入当前元素的时候,可以得到栈顶元素在数组右边第一个更大的值是当前元素。
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
stack = []
#栈里存储的是温度数组的下标
stack.append(0)
res = [0] * len(temperatures)
for i in range(1, len(temperatures)):
#遍历温度数组
#temperatures[i]小于等于栈顶元素
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
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
#精简
stack = []
res = [0] * len(temperatures)
for i in range(len(temperatures)):
while len(stack) > 0 and temperatures[i] > temperatures[stack[-1]]:
res[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return res
2.496.下一个更大元素 I
题目链接:496.下一个更大元素 I
文档讲解: 代码随想录
这道题还是用单调栈来做,从栈顶到栈底是递增的顺序,思路是一样的,根据题目要求,考虑到要在nums2对应位置往后寻找第一个更大的元素,因此需要遍历nums2。
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: 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
3.503.下一个更大元素II
题目链接:503.下一个更大元素II
文档讲解: 代码随想录
解决循环数组只需要遍历的过程中模拟走两遍。
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [-1] * len(nums)
stack = []
for i in range(len(nums) * 2):
while len(stack) > 0 and nums[i%len(nums)] > nums[stack[-1]]:
res[stack[-1]] = nums[i%len(nums)]
stack.pop()
stack.append(i%len(nums))
return res

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



