-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextgreaterelementI.cpp
More file actions
33 lines (29 loc) · 855 Bytes
/
NextgreaterelementI.cpp
File metadata and controls
33 lines (29 loc) · 855 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
33
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> nextGreater;
stack<int> st;
// Process nums2 to build next greater mapping
for (int num : nums2) {
while (!st.empty() && st.top() < num) {
nextGreater[st.top()] = num;
st.pop();
}
st.push(num);
}
// Remaining elements have no next greater
while (!st.empty()) {
nextGreater[st.top()] = -1;
st.pop();
}
// Build result for nums1
vector<int> result;
result.reserve(nums1.size());
for (int num : nums1) {
result.push_back(nextGreater[num]);
}
return result;
}
};