31. Next Permutation

80 篇文章 0 订阅

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,2,3”的全排列,依次是:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
所以题目的意思是,从上面的某一行重排到期下一行,如果已经是最后一行了,则重排成第一行。

另一位大神的解题思路如下:

以数组 6 5 4 8 7 5 1 为例,
首先肯定从后面开始看,1和5调换了没有用。
7、5和1调换了也没有效果,因此而发现了8、7、5、1是递减的。
如果想要找到下一个排列,找到递增的位置是关键。
因为在这里才可以使其增长得更大。
于是找到了4,显而易见4过了是5而不是8或者7更不是1。
因此就需要找出比4大但在这些大数里面最小的值,并将其两者调换。
那么整个排列就成了:6 5 5 8 7 4 1
然而最后一步将后面的8 7 4 1做一个递增。

根据上面的思路写了下面的代码:

public class Solution {
    public void nextPermutation(int[] nums) {
        int thenum = -1;
        int i = nums.length - 1;
        while (i > 0) {
            if (nums[i] > nums[i - 1]) {
                thenum = i - 1;
                break;
            }
            i --;
        }
        if (thenum != -1) {
            i = nums.length - 1;
            while (i > thenum) {
                if (nums[i] > nums[thenum]) {
                    int temp = nums[i];
                    nums[i] = nums[thenum];
                    nums[thenum] = temp;
                    break;
                }
                i --;
            }
        }
        for (i = 0; i < (nums.length - 1 - thenum) / 2; i ++) {
            int temp = nums[nums.length - 1 - i];
            nums[nums.length - 1 - i] = nums[thenum + 1 +i];
            nums[thenum + 1 +i] = temp;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值