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

[pull] master from youngyangyang04:master #482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
jenningsloy318 merged 5 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Sep 3, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
更新0503.下一个更大元素II的python版本
  • Loading branch information
JasenWn authored Aug 27, 2024
commit c5686b417d24a1d999d34ba9cf29d85ce77fe602
30 changes: 29 additions & 1 deletion problems/0503.下一个更大元素II.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ class Solution {
```

### Python:
> 版本一:

```python
class Solution:
Expand All @@ -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
Expand All @@ -203,7 +232,6 @@ func nextGreaterElements(nums []int) []int {
return result
}
```

### JavaScript:

```JS
Expand Down

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