leetcode 739 每日温度
对于单调栈问题,我觉得是在循环外部增加一些辅助项减少时间复杂度,但增加内存空间的利用
class Solution:def dailyTemperatures(self, temperatures: List[int]) -> List[int]:ans = [0] * len(temperatures)stack = []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]]:ans[stack[-1]] = i - stack[-1]stack.pop()stack.append(i)return ans
leetcode 496 下一个更大元素 |
审题!!!
class Solution:def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:ans = [-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]])ans[index] = nums2[i]stack.pop()stack.append(i)return ans
leetcode 503 下一个更大元素||
循环数组法一,两个相同数组串在一起:
class Solution:def nextGreaterElements(self, nums: List[int]) -> List[int]:ans = [-1] * len(nums)stack = [0]for i in range(len(nums) * 2):while len(stack) != 0 and nums[i % len(nums)] > nums[stack[-1]]:ans[stack[-1]] = nums[i % len(nums)]stack.pop()stack.append(i % len(nums))return ans
法二:同一个数组循环两遍