Skip to content

Commit 139e8e9

Browse files
Create next_greater_element_i.cpp
1 parent 237bfd2 commit 139e8e9

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

next_greater_element_i.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution {
2+
public:
3+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
4+
// Forward method
5+
// unordered_map<int, int> ump; //to keep track of nge for each element in nums2
6+
// //map of current element in stack => its nge
7+
// stack<int> st; //to store right part of search
8+
9+
// for(auto num : nums2) {
10+
// while(!st.empty() and st.top() < num) {
11+
// ump[st.top()] = num;
12+
// st.pop();
13+
// }
14+
// st.push(num);
15+
// }
16+
17+
// vector<int> result;
18+
// for(auto num : nums1) {
19+
// if(ump.find(num) != ump.end()) result.push_back(ump[num]);
20+
// else result.push_back(-1);
21+
// }
22+
23+
// return result;
24+
25+
//traverse backward
26+
if(nums1.size() == 0) return {};
27+
28+
int n = nums2.size();
29+
vector<int> result;
30+
31+
stack<int> st;
32+
unordered_map<int, int> ump;
33+
34+
for(int i=n-1; i>=0; i--) {
35+
36+
while(!st.empty() and st.top() < nums2[i]) st.pop();
37+
if(st.empty()) ump[nums2[i]] = -1;
38+
else ump[nums2[i]] = st.top();
39+
40+
st.push(nums2[i]);
41+
}
42+
43+
int m = nums1.size();
44+
for(auto num : nums1)
45+
result.push_back(ump[num]);
46+
47+
return result;
48+
}
49+
};

0 commit comments

Comments
 (0)