share my c++ solution, 9ms


  • 0
    X
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
    	    int len = nums.size();
            for(int i = nums.size() - 1; i > 0; i--){
    		    //if it is ascending order, then perform the sorting and replace 
    		    if(nums[i-1] < nums[i]){
    			    int pivot = nums[i-1];
    			    int next = pivot;
    			    sort(nums.begin() + i - 1, nums.end());
    			
    			    for(int j = i - 1; j < len - 1; j++){
    				    if (nums[j] == pivot && nums[j+1] > pivot){
    				        next = nums[j+1];
    					    nums.erase(nums.begin() + j+1);
    					    nums.insert(nums.begin() + i - 1, next);
    					    return;
    				    }
    			    }
    		    }
    	    }
    	    sort(nums.begin(), nums.end()); 
        }
        void swap(vector<int> &nums, int i, int j){
    	    int tmp = nums[i];
    	    nums[i] = nums[j];
    	    nums[j] = tmp;
        }
    };
    

Log in to reply
 

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