From 17a6cb3989befb0d6124f2854c17854dd46d62a1 Mon Sep 17 00:00:00 2001 From: 0zz10 <56071597+0zz10@users.noreply.github.com> Date: Sun, 21 Jan 2024 15:43:00 -0800 Subject: [PATCH] =?UTF-8?q?Update=200496.=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0I.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move solution from 0503.下一个更大元素II --- problems/0496.下一个更大元素I.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index 45797fb6..d97a3e84 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -256,6 +256,7 @@ class Solution { ### Python3 ```python +# 版本一 class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: result = [-1]*len(nums1) @@ -273,6 +274,26 @@ class Solution: stack.pop() stack.append(i) return result + +# 版本二 +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + # 创建答案数组 + ans = [-1] * len(nums1) + for i in range(len(nums2)): + while len(stack) > 0 and nums2[i] > nums2[stack[-1]]: + # 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常 + if nums2[stack[-1]] in nums1: + # 锁定 num1 检索的 index + index = nums1.index(nums2[stack[-1]]) + # 更新答案数组 + ans[index] = nums2[i] + # 弹出小元素 + # 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了 + stack.pop() + stack.append(i) + return ans ``` ### Go