31. Next Permutation (M)

本文详细解析了NextPermutation算法,介绍了如何在原地且仅使用常量额外内存的情况下,将数字序列重新排列成字典序上的下一个更大排列。若序列已处于最大排列,则返回最小排列。文章通过具体示例,阐述了算法的实现思路和步骤。

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

Next Permutation (M)

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, 3}为例,{1, 2, 3}是第一个排列,{3, 2, 1}则是最后一个排列。明确这一点才能展开下面的分析。

从序列末尾向前查找,直到第一次出现nums[i - 1] < nums[i],这说明第i及i之后的数为逆序排列,已达到该子序列的最大排列方式,需要更新该子序列前一位数字(即nums[i - 1]),这时只要从末尾查找,将第一个比nums[i - 1]大的数与nums[i - 1]交换,再将i及i之后的数字逆序,即可得到下一个排列。


代码实现

class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while (i >= 1 && nums[i] <= nums[i - 1]) {
            i--;
        }
        if (i == 0) {
            reverse(nums, 0, nums.length - 1);
        } else {
            int j = nums.length - 1;
            while (nums[j] <= nums[i - 1]) {
                j--;
            }
            int temp = nums[i - 1];
            nums[i - 1] = nums[j];
            nums[j] = temp;
            reverse(nums, i, nums.length - 1);
        }
    }

    private void reverse(int[] nums, int i, int j) {
        while (i <= j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值