Short O(n*n) solution


  • 1
    K
    class Solution {
    public:
        vector<int> nextGreaterElements(vector<int>& nums) {
            int n = nums.size();
            vector<int> gtr;
            for(int i=0; i<nums.size(); ++i){
                int j = (i + 1) % n;
                
                while(j != i && nums[i] >= nums[j]) {
                    j = (j + 1) % n;
                }
                if(j != i) gtr.push_back(nums[j]);
                else gtr.push_back(-1);
            }
            
            return gtr;
        }
    };

Log in to reply
 

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