Next Permutation

31. 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,31,3,2
3,2,11,2,3
1,1,51,5,1

题解

题目:求下一个增量最小的数,如果不存在,则将它们从高位到地位升序返回即可。

可以分为三步去求:

  1. 从尾部往前搜索,先找到第一个下降的数字,标记之。
    例子: 12431, 则我们找到的是 2
  2. 还是从尾往前搜索,找到第一个比2大的数字 ,交换之。
    12431 –> 13421
  3. 将421进行反序。这样我们就可以得到增量最小的数。
    13421 –> 13124
public class Solution {
    public void nextPermutation(int[] nums) {
        if(nums == null || nums.length < 2){
            return;
        }
        int exc = -1;
        for(int i = nums.length - 2;i >= 0;i--){
            if(nums[i] < nums[i+1]){
                exc = i;
                break;
            }
        }
        if(exc == -1){
            reverse(nums,0,nums.length-1);
            return;
        }
        // 交换
        for(int i = nums.length - 1;i > exc;i--){
            if(nums[i] > nums[exc]){
                int temp = nums[i];
                nums[i] = nums[exc];
                nums[exc] = temp;
                break;
            }
        }
        // 翻转
        reverse(nums,exc+1,nums.length-1);
    }
    private void reverse(int[] nums,int start,int end){
        for(int i=start,j=end;i<j;i++,j--){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    } 
}