mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2077 from Logenleedev/local-edit
problems/0503.下一个更大元素II.md 新的解法
This commit is contained in:
@ -99,7 +99,7 @@
|
||||
|
||||
这里我们可以写死,就是 如果只有两个元素,且元素不同,那么结果为 2。
|
||||
|
||||
不写死的话,如果和我们的判断规则结合在一起呢?
|
||||
不写死的话,如何和我们的判断规则结合在一起呢?
|
||||
|
||||
可以假设,数组最前面还有一个数字,那这个数字应该是什么呢?
|
||||
|
||||
|
@ -164,6 +164,7 @@ class Solution {
|
||||
|
||||
Python:
|
||||
```python
|
||||
# 方法 1:
|
||||
class Solution:
|
||||
def nextGreaterElements(self, nums: List[int]) -> List[int]:
|
||||
dp = [-1] * len(nums)
|
||||
@ -174,6 +175,26 @@ class Solution:
|
||||
stack.pop()
|
||||
stack.append(i%len(nums))
|
||||
return dp
|
||||
|
||||
# 方法 2:
|
||||
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:
|
||||
```go
|
||||
|
Reference in New Issue
Block a user