C++ solution O(nlogn)


  • 0
    H
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            if(nums.size()<=1)return;
            if(nums.size()==2)
            {
                swap(nums[0],nums[1]);
                return;
            }
            
            //find a unlexicographical permutation from the tail
            auto mov=nums.rbegin()+1;
            for(mov;mov<nums.rend();++mov)
            {
                if(*mov<*(mov-1))break;
            }
            
            //the whole vector is unlexicographical,so reverse
            if(mov==nums.rend())
            {
                reverse(nums.begin(),nums.end());
                return;
            }
    
            for(auto i=nums.rbegin();;++i)
            {
                if(*i>*mov)
                {
                    swap(*i,*mov);
                    break;
                }
            }
            sort(nums.rbegin(),mov,[](int a,int b){return a>b;});
        }
    };
    

Log in to reply
 

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