力扣刷题(第一百零一天)
灵感来源
- 保持更新,努力学习
- python脚本学习
下一个更大元素 I
解题思路
- 遍历
nums2
,使用单调栈找到每个元素的下一个更大元素,并通过哈希表存储对应关系。 - 遍历
nums1
,直接从哈希表中查询每个元素的下一个更大元素。class Solution:def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:# 哈希表存储nums2中每个元素的下一个更大元素next_greater = {}# 单调栈,用于寻找下一个更大元素stack = []# 遍历nums2,构建next_greater哈希表for num in nums2:# 当栈不为空且当前元素大于栈顶元素时,说明当前元素是栈顶元素的下一个更大元素while stack and num > stack[-1]:# 弹出栈顶元素,并记录其下一个更大元素为当前numtop = stack.pop()next_greater[top] = num# 将当前元素压入栈中,等待后续更大元素的出现stack.append(num)# 栈中剩余元素没有下一个更大元素,设置为-1while stack:top = stack.pop()next_greater[top] = -1# 遍历nums1,从哈希表中获取结果return [next_greater[num] for num in nums1]
逐行解释
class Solution:def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:# 哈希表:key为nums2中的元素,value为该元素的下一个更大元素next_greater = {}# 单调栈:用于临时存储尚未找到下一个更大元素的元素stack = []# 遍历nums2中的每个元素,寻找它们的下一个更大元素for num in nums2:# 核心逻辑:当当前元素大于栈顶元素时,栈顶元素的下一个更大元素就是当前元素# 循环处理栈中所有小于当前元素的元素while stack and num > stack[-1]:# 弹出栈顶元素(栈顶元素比当前元素小)top = stack.pop()# 记录栈顶元素的下一个更大元素为当前numnext_greater[top] = num# 将当前元素压入栈中,等待后续更大的元素出现stack.append(num)# 处理栈中剩余的元素:这些元素在nums2中没有下一个更大元素while stack:top = stack.pop()next_greater[top] = -1# 遍历nums1,从哈希表中直接获取每个元素的下一个更大元素return [next_greater[num] for num in nums1]