From c5686b417d24a1d999d34ba9cf29d85ce77fe602 Mon Sep 17 00:00:00 2001 From: Jasen <141482690+JasenWn@users.noreply.github.com> Date: Tue, 27 Aug 2024 22:32:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B00503.=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0II=E7=9A=84python?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0503.下一个更大元素II.md | 30 +++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index 62066d85..5751bb91 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -168,6 +168,7 @@ class Solution { ``` ### Python: +> 版本一: ```python class Solution: @@ -181,6 +182,34 @@ class Solution: stack.append(i%len(nums)) return dp ``` + +> 版本二:针对版本一的优化 + +```python3 +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + res = [-1] * len(nums) + stack = [] + #第一次遍历nums + for i, num in enumerate(nums): + while stack and num > nums[stack[-1]]: + res[stack[-1]] = num + stack.pop() + stack.append(i) + #此时stack仍有剩余,有部分数‘无下一个更大元素’待修正 + #第二次遍历nums + for num in nums: + #一旦stack为空,就表明所有数都有下一个更大元素,可以返回结果 + if not stack: + return res + while stack and num > nums[stack[-1]]: + res[stack[-1]] = num + stack.pop() + #不要将已经有下一个更大元素的数加入栈,这样会重复赋值,只需对第一次遍历剩余的数再尝试寻找下一个更大元素即可 + #最后仍有部分最大数无法有下一个更大元素,返回结果 + return res +``` + ### Go: ```go @@ -203,7 +232,6 @@ func nextGreaterElements(nums []int) []int { return result } ``` - ### JavaScript: ```JS