leetcode第31题——next permutation(超过100%的解法)

本文介绍了一种寻找字典次序下数组的下一个更大排列的方法。通过从右至左找到可以与后方更大元素交换的最右侧位置,然后进行元素交换及后续排序,实现原地更改并使用常数额外内存。

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

问题描述
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
解法思路
怎么找到字典次序下的下一个序列。字典次序前面的数所占的比重比后面大。因此找最近的从右端项找起。找到最右边的位置,该位置后存在比该位置元素更大的数,交换两数(另一个数为更右边的比该位置数更大的数中最小的)的位置,该位置以后的元素按照升序排列。
C++代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n=nums.size();
        vector<int> dp(n,-1);
        int left=-1;//代表位置交换的左端数位置
        for(int i=n-2;i>=0;--i)
        {
            int flag=INT_MAX;
            for(int j=i+1;j<n;++j)
            {
                if(nums[j]>nums[i])
                {
                    if(nums[j]<flag)
                    {
                        dp[i]=j;
                        flag=nums[j];
                    }
                }
            }
            if(dp[i]!=-1)
            {
                int a=nums[i];
                nums[i]=nums[dp[i]];
                nums[dp[i]]=a;
                left=i;
                break;
            }
        }
        if(left!=-1)//将left后面的元素按照升序排列,采用冒泡排序
        {
            for(int i=left+1;i<n-1;++i)
            {
                for(int j=left+1;j<n-i+left;++j)
                {
                    if(nums[j]>nums[j+1])
                    {
                        int a=nums[j];
                        nums[j]=nums[j+1];
                        nums[j+1]=a;
                    }
                }
            }
        }
        else
        {
            sort(nums.begin(),nums.end());
        }
    }
};

算法结果
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Next Permutation.
Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Next Permutation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值