LeetCode | # 31. Next Permutation

本文详细解析了NextPermutation算法,介绍了如何实现数组元素的字典序下一个排列。通过从右往左查找逆序位置,交换元素并反转子数组,实现了在原地使用常数额外内存完成任务。

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

31. Next Permutation

Description
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
Solution: (Java)
class Solution {
    public void nextPermutation(int[] nums) {
        int swap_index = -1, temp;
        for (int i = nums.length-2; i >= 0; i--) {
            if (nums[i] < nums[i+1]) {
                // 从右往左,找到第一个逆序的位置
                swap_index = i;
                for (int j = nums.length-1; j > swap_index; j--) {
                    if (nums[j] > nums[swap_index]) {
                        // 从右往左(也可以从左往右,找到最后一个比逆序位置数大的),找到第一个比逆序位置数大的,交换两者
                        temp = nums[swap_index];
                        nums[swap_index] = nums[j];
                        nums[j] = temp;
                        break;
                    }
                }
                break;
            }
        }
        int left = swap_index+1;
        int right = nums.length-1;
        // 将后面的降序的数组翻转为升序
        while (left < right) {
            temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}
思路

题意为找出一个数组全排列的下一个排列,举例:{1,2,3}的全排列为{123,132,213,231,312,321},那么123的下一个全排列为132,312的下一个全排列为321。解题流程如下:

  • 从右往左,找到第一个逆序(减小)的位置(因为后面如果是降序的,那无论如何交换都不能比给出的全排列大)
  • 从右往左(也可以从左往右,找到最后一个比逆序位置数大的),找到第一个比逆序位置数大的,交换两者
  • 将后面的降序的数组翻转为升序(因为下一个排列需满足:比给出的全排列大且是最小的)

结合字典序全排列的特性就好理解了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值