File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments