LeetCode 31 - Next Permutation

本文介绍了一个名为NextPermutation的算法实现,该算法用于将一组数字重新排列为字典序中下一个更大的排列。若无法形成更大排列,则将其重排为最小可能的顺序。算法采用原地替换方式,不分配额外内存。

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

My Code

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int size = nums.size();
        if (size < 1)
            return;

        int max = nums.back();

        int i = size - 2;
        for (; i >= 0; i--)
        {
            if (nums[i] < max)
            {
                int greater = max + 1;
                int idx = -1;
                for (int j = i + 1; j < size; j++)
                    if (nums[j] > nums[i] && nums[j] < greater)
                    {
                        greater = nums[j];
                        idx = j;
                    }

                nums[idx] = nums[i];
                nums[i] = greater;

                sort(nums.begin()+i+1, nums.end());

                break;
            }
            else
                max = nums[i];
        }

        if (i == -1)
            sort(nums.begin(), nums.end());
    }
};
Runtime: 12 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EnjoyCodingAndGame

愿我的知识,成为您的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值