代码随想录算法训练营四十八天|739.每日温度、496.下一个更大元素 I、503.下一个更大元素II
题目链接:739. 每日温度 - 力扣(LeetCode)
class Solution(object):def dailyTemperatures(self, temperatures):""":type temperatures: List[int]:rtype: List[int]"""answer = [0] * len(temperatures)stack = [0]for i in range(1, len(temperatures)):if temperatures[i] <= temperatures[stack[-1]]:stack.append(i)else:while len(stack) != 0 and temperatures[i] > temperatures[stack[-1]]:answer[stack[-1]] = i - stack[-1]stack.pop()stack.append(i)return answer
题目链接:496. 下一个更大元素 I - 力扣(LeetCode)
class Solution(object):def nextGreaterElement(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""from collections import defaultdicthelpDict = defaultdict(int)helpStack = [0]for i in range(1, len(nums2)):if nums2[i] <= nums2[helpStack[-1]]:helpStack.append(i)else:while len(helpStack) != 0 and nums2[helpStack[-1]] < nums2[i]:helpDict[nums2[helpStack[-1]]] = nums2[i]helpStack.pop()helpStack.append(i)answer = [-1] * len(nums1)for i in range(len(nums1)):if helpDict[nums1[i]] != 0:answer[i] = helpDict[nums1[i]]return answer
题目链接:503. 下一个更大元素 II - 力扣(LeetCode)
class Solution(object):def nextGreaterElements(self, nums):""":type nums: List[int]:rtype: List[int]"""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