-
Notifications
You must be signed in to change notification settings - Fork 0
/
next greater element i
50 lines (47 loc) · 1.33 KB
/
next greater element i
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
38
39
40
41
42
43
44
45
46
47
48
49
50
//it is of the order of m*n........
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int n = nums2.size();
stack<int> nextG;
stack<int> temp;
for(int i=n-1; i>=0; i--){
if(temp.empty()){
nextG.push(-1);
temp.push(nums2[i]);
}
else if(temp.top()>nums2[i]){
nextG.push(temp.top());
temp.push(nums2[i]);
}
else{
while(!temp.empty() && temp.top()<nums2[i]){
temp.pop();
}
if(!temp.empty()){
nextG.push(temp.top());
}
else{
nextG.push(-1);
}
temp.push(nums2[i]);
}
}
vector<int> ans;
while(!nextG.empty()){
// cout<<nextG.top()<<" ";
ans.push_back(nextG.top());
nextG.pop();
}
vector<int> finalAns;
for(int i=0; i<(int)nums1.size(); i++){
for(int j=0; j<n; j++){
if(nums1[i]==nums2[j]){
finalAns.push_back(ans[j]);
break;
}
}
}
return finalAns;
}
};