forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0496-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
classSolution:
defnextGreaterElement(self, nums1: List[int], nums2: List[int]) ->List[int]:
# O (n + m)
nums1Idx= { n:ifori, ninenumerate(nums1) }
res= [-1] *len(nums1)
stack= []
foriinrange(len(nums2)):
cur=nums2[i]
# while stack exists and current is greater than the top of the stack
whilestackandcur>stack[-1]:
val=stack.pop() # take top val
idx=nums1Idx[val]
res[idx] =cur
ifcurinnums1Idx:
stack.append(cur)
returnres
# O (n * m)
nums1Idx= { n:ifori, ninenumerate(nums1) }
res= [-1] *len(nums1)
foriinrange(len(nums2)):
ifnums2[i] notinnums1Idx:
continue
forjinrange(i+1, len(nums2)):
ifnums2[j] >nums2[i]:
idx=nums1Idx[nums2[i]]
res[idx] =nums2[j]
break
returnres