leetcode 496 下一个更大元素 I
z

给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

链接:https://leetcode-cn.com/problems/next-greater-element-i

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
ans = []
for i in nums1:
start_idx = nums2.index(i)
exist = False
for j in range(start_idx, len(nums2)):
if nums2[j] > i:
ans.append(nums2[j])
exist = True
break
if not exist:
ans.append(-1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 保持一个降序的站,每次来新的元素,从栈的右端排出比当前元素小的元素,每次排出时,判断排出的数是否是nums1中的
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
ans = [-1 for i in range(len(nums1))]
stack = []
for i in nums2:
if not stack:
stack.append(i)
else:
if stack[-1] >= i:
stack.append(i)
continue
else:
while stack and stack[-1] < i:
out = stack.pop()
if out in nums1:
ans[nums1.index(out)] = i
stack.append(i)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dic = {}
stack = []
for i in nums2:
if not stack:
stack.append(i)
else:
if stack[-1] >= i:
stack.append(i)
continue
else:
while stack and stack[-1] < i:
dic[stack.pop()] = i
stack.append(i)
return [dic[i] if i in dic.keys() else -1 for i in nums1]