leetcode31. Next Permutation

中等难度题目,实现一个函数找到一个数列的字典顺序下一个排列。如果无法找到更优排列,则将其转换为升序排列。必须原地修改,不使用额外内存。解题思路包括找到第一个降序对并进行交换及后续部分的逆序操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

medium程度题

题目:

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.从右到左找到第一个不符合升序排列的数字m

2.从右到左,找到第一个比m大的数字n

3.交换m和n的位置

4.将m后面一个位置到数组尾的所有元素逆序

AC解

class Solution {
public:
    void nextPermutation(vector<int>& nums)
    {
        int size = nums.size();
        if (size <= 1)
            return ;
            
        int max_index = INT_MAX;
        int len = size - 1;
        
        //找到m的位置
        while (len > 0)
            if (nums[len] > nums[len - 1])
            {
                max_index = len - 1;
                break;
            }
            else  len--;
         //如果找不到,则整个序列是递减的,逆序所有元素  
        if (len == 0)
        {
            reverse(nums,0,size - 1);
            return ;
        }
        //找到n的位置
        int greater = size - 1;
        while(nums[greater--] <= nums[max_index]);
        greater++;
	//交换m,n 	逆序
        swap(nums[max_index],nums[greater]);
        reverse(nums,max_index + 1,size - 1);
    }
    
    void reverse(vector<int> &vec,int i,int j)
    {
        while (i < j)
        {
            swap(vec[i],vec[j]);
            i++;
            j--;
        }
    }
};


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值