LeetCode Java First 400 题解-031

本文详细解析了NextPermutation算法,介绍了如何实现数字序列的字典序下一个排列。通过从个位向高位查找,确定需要置换的数字,并进行相应的置换和序列调整,以达到算法目标。适用于需要处理数字序列排列问题的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Next Permutation    Medium

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

public void nextPermutation(int[] nums) {

    int i;

    for (i = nums.length - 1; i > 0; --i)

        if (nums[i] > nums[i - 1])

            break;

    if (i > 0)

        for (int j = nums.length - 1; j >= i; --j)

            if (nums[j] > nums[i - 1]) {

                swap(nums, j, i - 1);

                break;

            }

    reverse(nums, i, nums.length - 1);

}

 

private static void swap(int[] nums, int i, int j) {

    int temp = nums[i];

    nums[i] = nums[j];

    nums[j] = temp;

}

 

private static void reverse(int[] nums, int i, int j) {

    while (i < j)

        swap(nums, i++, j--);

}

思路:找下一个排列中略大于现在数的数。如果这个数存在,则数组中一定有一个低位数大于某一高位数。从个位开始向高位逐一查找,看相邻两数是否高位的较小(注意相邻两数的关系已经决定了数列的单调性),如果是,那么需要找一个大于它的数和它置换。可以证明高位之后的数字是递减排列,所以从最低位找到第一个大于该高位的数与之置换,则新数一定大于当前数,且该高位后为递减排列,这时需要把这部分倒置为递增排列。如果这个数不存在,可以证明,整个数组是递减排列,整体倒置即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值