forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0496-next-greater-element-i.cpp
More file actions
32 lines (28 loc) · 934 Bytes
/
0496-next-greater-element-i.cpp
File metadata and controls
32 lines (28 loc) · 934 Bytes
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
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
// O (n + m)
map<int, int> nums1Idx; {
int idx = 0;
for(int n: nums1)
nums1Idx[n] = idx++;
}
vector<int> res;
for(int i = 0; i < nums1.size(); i++)
res.push_back(-1);
stack<int> stack;
for(int i = 0; i < nums2.size(); i++) {
int cur = nums2[i];
// while stack has elements and current is greater than the top of the stack
while(stack.size() && cur > stack.top()) {
int val = stack.top(); // take top val
stack.pop();
int idx = nums1Idx[val];
res[idx] = cur;
}
if(nums1Idx.count(cur))
stack.push(cur);
}
return res;
}
};