LeetCode #31 - 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


题意为找出某个数的全部数字的下一个排列,思路为从低位开始找出一个单增序列,从而确定第一个非单增数nums[pos1],并从单增序列中找出恰好比这个数大的最小数nums[pos2],将这两个数交换,并翻转pos1之后的所有数。注意当原数字已经为最大排列时,需要单独判断,直接翻转。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int pos1=0;
        int pos2=0;
        bool flag=true;
        for(int i=nums.size()-2;i>=0;i--)
        {
            pos1=i;
            if(nums[i]<nums[i+1]) 
            {
                flag=false;
                break;
            }
        }
        if(flag) 
        {
            reverse(nums.begin(),nums.end());
            return;
        }
        
        for(int i=pos1+1;i<nums.size();i++)
        {
            pos2=i;
            if(i==(nums.size()-1)||nums[i+1]<=nums[pos1]) break;
        }
        swap(nums[pos1],nums[pos2]);
        reverse(nums.begin()+pos1+1,nums.end());
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值