【leetcode】Next Permutation(middle)

本文介绍了一个用于重新排列数字数组以获得下一个更大排列的算法。详细解释了如何在原地完成此操作,避免使用额外内存,并提供了实现代码示例。

摘要生成于 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, 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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

思路:

首先,从后向前找到第一对递增的的数 如 1 4 2 5 7 6 3 中的 5 7, 这表示,7 6 3 是一个连续递减的序列,即这三个数字可以组成的最大的数。 把这三个数翻转,就是 3 6 7即这三个数字可以组成的最小的数字。把5与这三个数字中比它大的最小的数字与它交换变成 1 4 2 6 7 5 3,即下一个较大的数字。注意,像2 3 1 3 3 这样后面比交换点数大一点的数有相同的时候,后面翻转后,交换后面的那个。

class Solution {
public:
    void nextPermutation(vector<int> &num) 
    {
        if (num.empty()) return;

        // in reverse order, find the first number which is in increasing trend (we call it violated number here)
        int i;
        for (i = num.size()-2; i >= 0; --i)
        {
            if (num[i] < num[i+1]) break;
        }

        // reverse all the numbers after violated number
        reverse(begin(num)+i+1, end(num));
        // if violated number not found, because we have reversed the whole array, then we are done!
        if (i == -1) return;
        // else binary search find the first number larger than the violated number
        auto itr = upper_bound(begin(num)+i+1, end(num), num[i]);
        // swap them, done!
        swap(num[i], *itr);
    }
};

 

 

我自己写得:思路是先交换,再翻转。比上面的繁琐一点。

void nextPermutation(vector<int> &num) {
        if(num.empty()) return;
        bool b = false;
        int chg1 = 0, chg2 = 0;
        int post = num.size() - 1;
        for(int i = num.size() - 2; i >= 0; --i)
        {
            if(num[post] > num[i])
            {
                b = true;
                chg1 = i; 
                chg2 = post;
                break;
            }
            post = i;
        }

        if(!b)
        {
            reverse(num.begin(), num.end());
            return;
        }

        for(int i = chg1 + 1; i < num.size(); i++)
        {
            if(num[i] > num[chg1] && num[i] <= num[chg2])
                chg2 = i;
        }
        swap(num[chg1], num[chg2]);

        int l1 = chg1 + 1;
        int l2 = num.size() - 1;
        while(l1 < l2)
        {
            swap(num[l1++], num[l2--]);
        }
        return;
    }

 

转载于:https://www.cnblogs.com/dplearning/p/4459923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值