-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0496-next-greater-element-i.py
37 lines (28 loc) · 1.06 KB
/
0496-next-greater-element-i.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
# O (n + m)
nums1Idx = { n:i for i, n in enumerate(nums1) }
res = [-1] * len(nums1)
stack = []
for i in range(len(nums2)):
cur = nums2[i]
# while stack exists and current is greater than the top of the stack
while stack and cur > stack[-1]:
val = stack.pop() # take top val
idx = nums1Idx[val]
res[idx] = cur
if cur in nums1Idx:
stack.append(cur)
return res
# O (n * m)
nums1Idx = { n:i for i, n in enumerate(nums1) }
res = [-1] * len(nums1)
for i in range(len(nums2)):
if nums2[i] not in nums1Idx:
continue
for j in range(i + 1, len(nums2)):
if nums2[j] > nums2[i]:
idx = nums1Idx[nums2[i]]
res[idx] = nums2[j]
break
return res