share my c++ solution in 9ms


  • 0
    K
    void nextPermutation(vector<int>& nums) {
            if(nums.size()>1){
                int f=nums.size()-2;
                while(f>=0){
                    int j=f+1,min=0;
                    bool hasB=false;
                    for(;j<nums.size();j++){
                        if(nums[j]>nums[f] && hasB==false){
                            hasB=true;
                            min=j;
                        }
                        else if(nums[j]>nums[f] && hasB==true && nums[j]<nums[min]){
                            min=j;
                        }
                    }
                    if(hasB){
                        int temp=nums[min];
                        nums[min]=nums[f];
                        nums[f]=temp;
                        sort(nums.begin()+f+1,nums.end());
                        break;
                    }
                    else{
                        f--;
                    }
                }
                if(f<0){
                    sort(nums.begin(),nums.end());
                }
                
            }
        }
    

Log in to reply
 

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