LeetCode 31 — Next Permutation(下一个排列)

这篇博客介绍了如何实现LeetCode第31题的解决方案,即找到给定数字序列的字典序下一个更大排列。如果无法找到更大排列,则应将其转换为升序排列。文章通过举例解释了题目的要求,并详细分析了解决问题的思路,包括从右向左查找最小且大于当前元素的数字进行交换,然后对交换后的部分进行升序排列。当无法找到满足条件的元素时,只需对整个序列进行两两交换以得到最小字典序排列。最后,文章提到了利用异或操作来优化算法的效率。

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

翻译
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
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) {
        bool find = false;
        for (int i = nums.size()-2; i >= 0; i--)
        {
            int tmp = INT_MAX,pos;
            for (int j = i+1;  j < nums.size(); j++)
            {
                if (nums[j] > nums[i] && nums[j] < tmp)
                {
                    tmp = nums[j];
                    pos = j;
                    find = true;
                }
            }
            if (find)
            {
                nums[i] = nums[i]^nums[pos];
                nums[pos] = nums[pos]^nums[i];
                nums[i] = nums[i]^nums[pos];
                sort(nums.begin()+i+1,nums.end());
                return;
            }
        }
        int size = nums.size();
        for (int i = 0; i < size/2; i++)
        {
            nums[i] = nums[i]^nums[size-i-1];
            nums[size-i-1] = nums[i]^nums[size-i-1];
            nums[i] = nums[i]^nums[size-i-1];;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值