leetcode - Next Permutation

本文详细解析了NextPermutation算法,介绍了如何实现将数组重新排列为字典序中下一个更大的排列,若不存在则变为最小排列。核心步骤包括寻找关键下标并进行数值交换及排序。

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

题目:

Next Permutation


 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,31,3,2
3,2,11,2,3
1,1,51,5,1


分析:

题目的意思实际上是:除非输入数组为递减数组,否则就是把该数组代表的数字“变大”,且变大的值尽可能小。变大意味着数组肯定有某一个下标的值从小变成大。这个下标通过找规律,发现是 “步骤2” 中提到的i-1。找到这个下标后,便在其后面的数里找一个比nums[i-1]大的最小的数nums[index],交换nums[i-1]和nums[index]的值,然后把下标[i,size-1]内的数从小到大排序。

步骤:

1、若输入数组为递减数组,则从小到大排序后输出。

2、从后往前找到第一个下标i,使得nums[i]>nums[i-1],在下标[i,size-1]中找到比nums[i-1]大的最小的数nums[index],交换nums[i-1]和nums[index]的值,然后把下标[i,size-1]内的数从小到大排序。



class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int size=nums.size();
        if(size<=1)
            return;
        int i=size-1;
        for(;i>=1;--i)
        {
            if(nums[i]>nums[i-1])
                break;
        }
        if(i==0)
        {
           sort(nums.begin(),nums.end());
            return;
        }
        int index=i;
        for(int j=index+1;j<size;++j)
        {
            if(nums[j]>nums[i-1] && nums[index]>nums[j])
                index=j;
        }
        swap(nums[index],nums[i-1]);
        sort(nums.begin()+i,nums.end());
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值