Leetcode 31 Next Permutation

本文介绍了一个算法,用于寻找给定数字序列的下一个字典序更大的排列。如果不存在这样的排列,则将其重新排列为字典序最小的排列。算法通过从后向前扫描,找到可以交换的元素并进行最小化反转来实现。

摘要生成于 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

这个题的意思是找到下一个最大的排列数,方法类似于双指针,从后往前扫,当遇到可以进行更换的数的时候进行更换,并使用reverse进行反转后面的数,使得后面的数为最小的。

1)

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

2)

static const auto _______ = [](){//大概是一种特殊的读取数的形式
    std::cout.sync_with_stdio(false);
    cin.tie(0);
    return 0;
}();
class Solution {
public:
    void nextPermutation(vector<int>& a) {
        int n=a.size();    
        int i;
        for(i=n-1;i>0;i--) {
            if(a[i]>a[i-1])   {
                int k=i;
                for(int j=i;j<n;j++) {
                    if(a[j]>a[i-1]&&a[j]<a[k])
                        k=j;
                }
                swap(a[i-1],a[k]);
                break;
            }
        }
        sort(a.begin()+i,a.end());
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值