[LintCode] 52. Next Permutation

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: return nothing (void), do not return anything, modify nums in-place instead
     */
      public int[] nextPermutation(int[] nums) {
		int m = nums.length;
	       int i = 0;
	       for(i = m-1;i>=1;i--){
	    	   if(nums[i] > nums[i - 1]){ /*Find the inflection point from back to front, that is, the latter point is larger than the previous point, and the previous point is the inflection point**/
	    		   /*Find the smallest number after the inflection point (this number is larger than the inflection point)*
	    		    *Swap this number with the inflection point*
	    		    * Sort the numbers after the inflection point again */
	    		   int min = nums[i];
	    		   int index = i;
	    		   for(int k = i;k<m;k++){
	    			   if(nums[k] <= min && nums[k] > nums[i - 1]){
	    				   min = nums[k];
	    				   index = k;
	    			   }
	    		   }
	    		   int temp = nums[ i - 1];
	    		   nums[i - 1] = nums[index];
	    		   nums[index] = temp;
	    		   Arrays.sort(nums, i, nums.length);/*sort the numbers after the inflection point***/
	    		   break;
	    	   }
	       }
	       if(i == 0){
	    	   Arrays.sort(nums);
	       }
	       
	       return nums;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325506607&siteId=291194637