Stack do monotonically decreasing, time O (n), spaceO (n) requires a hash map
class Solution { public : Vector < int > nextGreaterElement (Vector < int > & nums1, Vector < int > & nums2) { // with a monotonically decreasing from the stack top to the stack bottom of the stack do this problem, traversing from right to left ; // 1. If the current element is greater than the top element, described on the right of the first element is larger than the x stack; // 2. If the current element is less than the top element, the top element pop put off, and then repeat the line guidance stack is empty; // because even after the next greater element of looking at the very least is the current element, because the current element from // closer after the elements, and greater value; int len1 = nums1.size (); IF (LEN1 == 0 ) return {}; Stack < int > s; unordered_map<int,int> m;//map<num2,nextgreater> vector<int> res; for(int i=nums2.size()-1;i>=0;i--){ while(!s.empty()){ if(s.top()>nums2[i]){ m[nums2[i]]=s.top();break; }else{ s.pop(); } } if(s.empty()){ m[nums2[i]]=-1; } s.push(nums2[i]); } for(int i=0;i<len1;i++){ res.push_back(m[nums1[i]]); } return res; } };