赞
踩
【代码随想录训练营】【Day 62】【单调栈-1】| Leetcode 739, 496, 503
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: answer = [0] * len(temperatures) stack = [] for i in range(len(temperatures)): if i == 0: stack.append(i) continue if temperatures[i] <= temperatures[stack[-1]]: stack.append(i) else: while len(stack) > 0 and temperatures[i] > temperatures[stack[-1]]: index = stack.pop() answer[index] = i - index stack.append(i) return answer
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
answer = [-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]]:
index = stack.pop()
if nums2[index] in nums1:
answer[nums1.index(nums2[index])] = nums2[i]
stack.append(i)
return answer
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: nums_new = nums + nums answer = [-1] * len(nums) * 2 stack = [0] for i in range(len(nums_new)): if nums_new[i] <= nums_new[stack[-1]]: stack.append(i) else: while len(stack) > 0 and nums_new[i] > nums_new[stack[-1]]: index = stack.pop() answer[index] = nums_new[i] stack.append(i) return answer[:len(nums)] # dp = [-1] * len(nums) # stack = [] # for i in range(len(nums)*2): # while(len(stack) != 0 and nums[i%len(nums)] > nums[stack[-1]]): # dp[stack[-1]] = nums[i%len(nums)] # stack.pop() # stack.append(i%len(nums)) # return dp
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。