leetcode ---next Permutation

本文介绍了一个算法问题:如何在原地且仅使用常量额外内存的情况下,将一组数字重新排列成字典序中下一个更大的排列。文章详细分析了解决方案,并通过示例展示了算法的工作原理。同时,提供了完整的Java代码实现。

一.题目

    

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

二.分析过程

  对于{1,2,5,4,3}想找下一个比这个序列大的,一定是替换后面的数字,如果替换前面的比如替换1,得到的结果会比这个序列大,但不能满足题目的意思,从后往前找,发现{2,5,4,3}该序列存在满足题目的序列,对于{5,4,3},{4,3}等是不存在的。而要得到next permutation,只需要从{5,4,3}取出比2大的元素中的最小一个替换2,在生成{5,4,2}的最小序列,跟原来的序列合并就得到想要的结果了,有点贪心法的意思,局部的最优解就是整体的最优解

三.代码实现

    

public class NextPermutation {
    public static void nexPermutation(int[] nums) {
        int i = nums.length - 1;
        //找到含有nexpermutation的子序列
        for (; i > 0 && nums[i] <= nums[i - 1]; i--) ;

        int start = i -1;

        //如果start不为0,说明存在下一个比当前序列大的序列,从后面子序列中找出大于nums[i]的元素最小元素替换他
        if (start >= 0) {
            int temp = nums[start];
            boolean changed = false;
            for (int j = i; j < nums.length; j++) {
                if (!changed) {
                    if (nums[j] > nums[start]) {
                        swap(nums, start, j);
                        changed = true;
                    }
                } else if (nums[j] > temp && nums[j] < nums[start]) {
                    swap(nums, start, j);
                }
            }
        }

        //生成后面子序列的最小序列
        generateMin(nums, i);

    }

    public static void generateMin(int[] nums, int i) {
        for (; i < nums.length - 1; i++) {
            for (int n = i + 1; n < nums.length; n++) {
                if (nums[i] > nums[n]) {
                    swap(nums, i, n);
                }
            }
        }
    }

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

    public static void main(String[] args) {
        int[] nums = {1, 2};
        nexPermutation(nums);
        Arrays.stream(nums).forEach(t -> {
            System.out.println(t);
        });

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值