Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

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.

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

 1 public class Solution {
 2     public void nextPermutation(int[] num) {
 3         int start = num.length-1;
 4         while(start>0 ){
 5             if(num[start-1]<num[start]) break;
 6             else{
 7                 start--;
 8             }
 9         }
10         if(start>0){
11             start--;
12             int end = num.length-1;
13             while(end>0 && num[start]>=num[end]){
14                 end--;
15             }
16             int temp = num[start];
17             num[start]  = num[end];
18             num[end] = temp;
19             start++;
20         }
21         int end = num.length-1;
22         while(start<end){
23             int temp = num[start];
24             num[start] = num[end];
25             num[end] = temp;
26             start++;
27             end--;
28         }
29     }
30 }
View Code

 

posted @ 2014-02-06 14:08  krunning  阅读(132)  评论(0编辑  收藏  举报