File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -168,6 +168,7 @@ class Solution {
168168```
169169
170170### Python:
171+ > 版本一:
171172
172173```python
173174class Solution :
@@ -181,6 +182,34 @@ class Solution:
181182 stack.append(i%len(nums))
182183 return dp
183184```
185+
186+ > 版本二:针对版本一的优化
187+
188+ ```python3
189+ class Solution:
190+ def nextGreaterElements(self, nums: List[int]) -> List[int]:
191+ res = [-1] * len(nums)
192+ stack = []
193+ #第一次遍历nums
194+ for i, num in enumerate(nums):
195+ while stack and num > nums[stack[-1]]:
196+ res[stack[-1]] = num
197+ stack.pop()
198+ stack.append(i)
199+ #此时stack仍有剩余,有部分数‘无下一个更大元素’待修正
200+ #第二次遍历nums
201+ for num in nums:
202+ #一旦stack为空,就表明所有数都有下一个更大元素,可以返回结果
203+ if not stack:
204+ return res
205+ while stack and num > nums[stack[-1]]:
206+ res[stack[-1]] = num
207+ stack.pop()
208+ #不要将已经有下一个更大元素的数加入栈,这样会重复赋值,只需对第一次遍历剩余的数再尝试寻找下一个更大元素即可
209+ #最后仍有部分最大数无法有下一个更大元素,返回结果
210+ return res
211+ ```
212+
184213### Go:
185214
186215``` go
@@ -203,7 +232,6 @@ func nextGreaterElements(nums []int) []int {
203232 return result
204233}
205234```
206-
207235### JavaScript:
208236
209237``` JS
You can’t perform that action at this time.
0 commit comments