Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.java
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).数组
The replacement must be in-place, do not allocate extra memory.spa
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
code
题意blog
给一个整型数组如num[] = 1, 3, 2,这个数组组成一个数组132,下一个比他大的是2,1,3。若是给定的数组存在这样的一个Next,把数组从新按照新的next排好序。若是不存在,好比3,2,1就不存在这样的,返回这个数组组成的最小整数1,2,3数组顺序也变为num[] = 1,2,3it
思路io
从最后开始遍历,若是出现num[i] > num[i - 1]说明存在这样的next,找出i后面的最小值和i - 1进行交换,在对i及i后面的数组进行降序排列。若是不存在这样的next,对数组进行升序排列。class
1 import java.util.Arrays; 2 3 public class Solution { 4 public void nextPermutation(int[] num) { 5 if(num.length == 0 || num.length == 1) 6 return; 7 boolean found = false; 8 int index = 0; 9 int comparaValue = 0; 10 for(int i = num.length - 1; i > 0; i--){ //找出出现降序的位置 11 if(num[i] > num[i - 1]){ //这里不能交换 12 index = i; 13 comparaValue = i - 1; 14 found = true; 15 break; 16 }//if 17 }//for 18 if(found){ //有可能 19 int min = index; 20 for(int i = min; i < num.length; i++){ 21 if(num[i] > num[comparaValue] && num[i] < num[min]){ 22 min = i; 23 }//if 24 }//for 25 int temp = num[min]; 26 num[min] = num[comparaValue]; 27 num[comparaValue] = temp; 28 29 //对index后面的进行升序排列 30 for(int i = index; i < num.length; i++){ 31 min = i; 32 for(int j = i + 1; j < num.length; j++){ 33 if(num[min] > num[j]) 34 min = j; 35 }//for 36 if(min != i){ 37 temp = num[min]; 38 num[min] = num[i]; 39 num[i] = temp; 40 } 41 } 42 }//if 43 else{ 44 Arrays.sort(num); 45 } 46 } 47 }