class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
stack<int> s;
unordered_map<int, int> m;
for (int n : nums) {
while (s.size() && s.top() < n) {
m[s.top()] = n;
s.pop();
}
s.push(n);
}
vector<int> ans;
for (int n : findNums) ans.push_back(m.count(n) ? m[n] : 1);
return ans;
}
};
C++ stack + unordered_map







Very cool solution. The only problem is it's not "pay for play". I.e., it precomputes the Next Greatest Element for all elements of nums. So, if the size of findNums is much smaller than that of nums (e.g. 1 vs 1000) all that effort is wasted. However, if they are of close to similar size, then this is optimal.