10-line C++ O(n) Solution, Simpler than Next Greater Element I


  • 0

    There are three changes compared with Next Greater Element I: 1, same vector; 2, circular; 3, duplicates allowed now. However, these in fact makes the solution simpler.
    1, same vector: simpler, we can eliminate the hash map thanks to this
    2, circular: just repeat the vector again
    3, duplicates: change to store index rather than value

    class Solution {
    public:
        vector<int> nextGreaterElements(vector<int>& nums) {
            vector<int> res(nums.size(),-1);
            stack<int> s;
            for(int i=0;i<nums.size()*2;i++){
                while(s.size()&&nums[s.top()]<nums[i%nums.size()]){
                    res[s.top()]=nums[i%nums.size()];
                    s.pop();
                }
                i<nums.size()?s.push(i):(void)0;
            }
            return res;
        }
    };

Log in to reply
 

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