Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0ff428

Browse files
Merge pull request youngyangyang04#2711 from JasenWn/master
更新0503.下一个更大元素II的python版本
2 parents cf8f9e8 + 78018c9 commit d0ff428

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

‎problems/0503.下一个更大元素II.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ class Solution {
168168
```
169169

170170
### Python:
171+
> 版本一:
171172

172173
```python
173174
class 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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /