【LeetCode】31. Next Permutation - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84782456

1. 题目描述:

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

2. 思路分析:

题目的意思是给定一个数组,找出数组中数的全排列的下一个情况,即找出下一个全排列。

下面这种算法据说是STL中的经典算法。在当前序列中,从尾端往前寻找两个相邻升序元素,升序元素对中的前一个标记为partition。然后再从尾端寻找第一个大于partition的元素,并与partition指向的元素交换,然后将partition后的元素(不包括partition指向的元素)逆序排列。比如14532,那么升序对为45,partition指向4,由于partition之后除了5没有比4大的数,所以45交换为54,即15432,然后将partition之后的元素逆序排列,即432排列为234,则最后输出的next permutation为15234。确实很巧妙。

3. Java代码:

源代码见我GiHub主页

代码:

public static void nextPermutation(int[] nums) {
    // 先从后往前找到第一次出现升序的2个数,i指向前一个数
    int i = nums.length - 2;
    while (i >= 0 && nums[i] >= nums[i + 1]) {
        i--;
    }

    // 然后从后往前找到第一个大于nums[i]的数
    if (i >= 0) {
        int j = nums.length - 1;
        while (nums[j] <= nums[i]) {
            j--;
        }
        // 交换2个下标对应的元素
        swap(nums, i, j);
    }
    // 逆置i之后的所有元素
    reverse(nums, i + 1);
}

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

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

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84782456