LeetCode Next Permutation

本文介绍了一个算法问题——如何找出一个整数序列的下一个字典序排列。通过从右向左扫描并找到第一个破坏降序规律的元素,然后找到其右侧大于它的最小元素进行交换,并将该元素之后的部分反转为升序,以此得到下一个排列。

mplement 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

本题在于如何分析转换的特性。当按照降序排列为最大,升序排列为最小。首先按照从右往左开始寻找不符合降序排列的数记为A,在A的右边区域寻找最小的大于A的数B,然后交换A,B,此时B的右边区域

仍然是降序排列,将右边区域转换为升序排列,则所求的数即为解。

代码如下:

class Solution {
public:
    void swap(vector<int>& nums,int i,int j)
    {
        nums[i] = nums[i]^nums[j];
        nums[j] = nums[i]^nums[j];
        nums[i] = nums[i]^nums[j];
    }
    
    void reverse(vector<int>& nums,int start)
    {
        int i=start,j=nums.size()-1;
        while(i<j)
        {
            swap(nums,i,j);
            i++;
            j--;
        }
    }
    
    void nextPermutation(vector<int>& nums) {
        int i=nums.size()-2;
        while(i>=0 && nums[i+1] <= nums[i])
            i--;
        
        if(i>=0)
        {
            int j = nums.size()-1;
            while(j>i && nums[j] <= nums[i])
                j--;
        
            swap(nums,i,j);
        }
        reverse(nums,i+1);
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值