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

分析思路

首先,我们来看一个简单的例子
比如158476531这个序列,我们如果只想它变大一点点,应该尽可能的不去增加高位。因为增加高位会带来更大的增益。所以对于一个长为n的序列,我们增加第n位的前提是,前n-1位已经达到了最大排列方法。所以我们从后往前看

1
31
531
6531
76531

上边列举的都是一个升序的序列,不可能变得更大了,先不动它。
然后,可以将4移到后面来来增大。但是问题在于,把谁移到4的位置。因为是找下一个数,所以我们要找一个比4小却尽可能大的数,所以找到5,交换变成576431。
把5换到4的位置后,后几位(76431)仍然是个降序的排列,要做成一个以5开头最小的序列,而这个序列应该是升序的,所以我们直接把76431倒置一下,就从降序变成升序了。
下面是一个找next permutation的动画:
这里写图片描述

代码

public void nextPermutation(int[] nums) {
        if (nums.length <= 1) {
            return;
        }
        int i = nums.length - 2;
        // 找到第一个下降点,我们要把这个下降点的值增加一点点
        //511特殊,要加=,下边同理
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        // 如果这个下降点还在数组内,我们找到一个比它稍微大一点的数替换       
        if (i >= 0) {
            int j = nums.length - 1;
            while (j > i && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        // 如果在之外,说明整个数组是降序的,是全局最大了
        // 将下降点之前的部分倒序构成一个最小序列
        reverse(nums, i + 1, nums.length - 1);
    }

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

    private void reverse(int[] nums, int left, int right) {
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值