算法31. 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 and use only constant 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

class Solution {
    public void nextPermutation(int[] nums) {
        
    }
}

实现“next permutation”,重新排序数组,组成更大(lexicographically next greater,不是最大,并且只大一点点的)数值。
如果不能找到更大的,就返回最小的排序结果。
必须以“in-place”算法实现,且使用常量的额外内存。

“in-place”,原地算法,就是以固定额外内存,进行交换。
就按照例子中的,一个思路为:从末尾开始遍历,如果发现当前数比前一个小,则不变,如果大,则将前一个数与后面的数进行比较,交换刚好小于并且大于后面的那个数。如果走了一圈,发现为例子二中的情况,则交换整个数组的顺序。

以下为代码:

public void nextPermutation(int[] nums) {
    int i = nums.length - 2;
    // 找到当前数,比前一个数大的情况
    while (i >= 0 && nums[i + 1] <= nums[i]) {
        i--;
    }
    if (i >= 0) {
        int j = nums.length - 1;
        // 找到刚好比当前数小,且比后面一个数大的那个数
        while (j >= 0 && nums[j] <= nums[i]) {
            j--;
        }
        swap(nums, i, j);
    }

    // 这种就是全都是倒序的
    reverse(nums, i + 1);
}

private void reverse(int[] nums, int start) {
    int i = start, j = nums.length - 1;
    while (i < j) {
        swap(nums, i, j);
        i++;
        j--;
    }
}

private void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

你可能感兴趣的:(算法31. Next Permutation)