C++ Solution


  • 0
    F

    If the end of the loop is reached without getting greater element, then reset the inner loop from the beginning if all the elements of vector were not searched.

    vector<int> nextGreaterElements(vector<int>& nums) {
            vector<int> vec;
            for(int i=0;i<nums.size();i++){
                int next_greater=INT_MAX;
                int count=0;
                int circular_loop=nums.size();
                for(int j=i;j<circular_loop;j++){
                    if(nums[j] > nums[i]){
                            next_greater=nums[j];
                            vec.push_back(next_greater);
                            break;
                    }
                    count++;
                    if(j==nums.size()-1 && next_greater==INT_MAX && count<nums.size()){
                        j=-1;
                        circular_loop=nums.size()-count;
                    }            
                }                      
                if(next_greater==INT_MAX)
                    vec.push_back(-1);
            }
            return vec;
        }
    

Log in to reply
 

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