Next Permutation

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,1code

題意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 }
相關文章
相關標籤/搜索