[leetcode] 31. Next Permutation 解题报告

题目链接:https://leetcode.com/problems/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


思路:求下一个字典序有个规则。比如1,2,3,4,5,6这六个数的的第一个字典序是递增排列的1,2,3,4,5,6,最后一个排列是逆序排列的6,5,4,3,2,1。

举个栗子:6,3,5,4,2,1,要找这个数的下一个字典序,有下列步骤完成:

1. 从右往左找到第一个比右边数小的数3

2. 然后从这个数右边5开始往右找最后一个比3大的数4

3. 交换这两个值,则现在数组变成6,4,5,3,2,1

4. 现在将4后面的数排列成递增序列,即将其就地逆序,之后的数组将变成6,4,1,2,3,5,这个序列就是我们要求的下一个字典序。

代码如下:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int len = nums.size(), i = len -1;
        if(len == 0) return;
        while(i > 0 && nums[i-1] >= nums[i])//找到第一个比右边小的数
            i--;
        if(i == 0)//完全逆序则就地逆置
        {
            reverse(nums.begin(), nums.end());
            return;
        }
        int left = i-1;
        while(i < len && nums[i] > nums[left])//找到最后一个比left值大的数
            i++;
        swap(nums[i-1], nums[left]);
        i = left +1;
        reverse(nums.begin()+i, nums.end());//就地逆置后面的数组
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值