c++ O(n) solution


  • 0
       vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
            unordered_map<int,int> ht;
            stack<int> stk;
            for(int i=0;i<nums.size();i++) {
                while(!stk.empty() && nums[stk.top()]<nums[i]) { 
                    ht[nums[stk.top()]]=nums[i];
                    stk.pop();
                }
                stk.push(i);
            }
            int n = findNums.size();
            vector<int> res(n);
            for(int i=0;i<n;i++) {
                auto it = ht.find(findNums[i]);
                res[i]=it==ht.end()?-1:it->second;
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.