concise c++ solution using stack that beats 98%


  • 1
     vector<int> nextGreaterElements(vector<int>& nums) {
            int n = nums.size();
            vector<int> vec(n, -1);
            stack<int> stack;
            for(int i=0, j=0; i<2*n-1; i++){
                j = (i<n)?i:i-n;
                while(!stack.empty() && nums[stack.top()]<nums[j]){
                    vec[stack.top()] = nums[j];
                    stack.pop();
                }
                if(i<n)stack.push(i);
            }
            return vec;
        }
    

Log in to reply
 

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