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 7bd1160

Browse files
Merge pull request youngyangyang04#2421 from 0zz10/patch-2
Update 0496.下一个更大元素I.md
2 parents 95f1d8a + 17a6cb3 commit 7bd1160

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

‎problems/0496.下一个更大元素I.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ class Solution {
256256
### Python3
257257

258258
```python
259+
# 版本一
259260
class Solution:
260261
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
261262
result = [-1]*len(nums1)
@@ -273,6 +274,26 @@ class Solution:
273274
stack.pop()
274275
stack.append(i)
275276
return result
277+
278+
# 版本二
279+
class Solution:
280+
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
281+
stack = []
282+
# 创建答案数组
283+
ans = [-1] * len(nums1)
284+
for i in range(len(nums2)):
285+
while len(stack) > 0 and nums2[i] > nums2[stack[-1]]:
286+
# 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常
287+
if nums2[stack[-1]] in nums1:
288+
# 锁定 num1 检索的 index
289+
index = nums1.index(nums2[stack[-1]])
290+
# 更新答案数组
291+
ans[index] = nums2[i]
292+
# 弹出小元素
293+
# 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了
294+
stack.pop()
295+
stack.append(i)
296+
return ans
276297
```
277298

278299
### Go

0 commit comments

Comments
(0)

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