【leetcode】31. Next Permutation 数字序列的所有组合中比给定串大的下一个最小的串...

本文介绍了一个算法问题“下一个排列”的解决方案,该问题要求在给定数组中找到字典序上更大的排列,若不存在则变为最小排列。文章详细阐述了实现思路:从后向前找到第一个逆序点,再找到逆序点后大于其的最小数值并交换,最后反转逆序点后的子数组。

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

1. 题目

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

2. 思路

根据规则,从后往前找到第一个逆序点,然后从这个点开始后,找到最小的大于逆序点小值的数,二者兑换后,对后面的整体进行反转。
即a0a1a2...aN-1的数下,找到 a[i]<a[i+1] && a[i+1]>a[i+2]>....>a[N-1]。
然后找到a[j]>a[i] && a[j+1]<=a[i], 对调i,j后,a[i+1,....,N-1]形成非升序,翻转为非降序即可。

3. 代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        // 从末尾开始, 找到第一个逆序点i, 即a[i] < a[i+1] && a[i+1] >= a[i+2] >= ... >= a[N-1]
        // 在[i+1, N-1]范围内找到最小的比a[i]大的数a[j]; i,j 对调后,对[i+1, N-1]进行反转
        if (nums.size() < 2) return ;
        int i = nums.size() - 2;
        for (; i >= 0; i--) {
            if (nums[i] < nums[i+1]) {
                break;
            }
        }
        if (i < 0) {
            sort(nums.begin(), nums.end());
            return ;
        }
        int j = i + 1;
        int ni = nums[i];
        for (; j < nums.size(); j++) {
            if (nums[j] <= ni) {
                break;
            }
        }
        j--;
        nums[i] = nums[j];
        nums[j] = ni;
        std::reverse(nums.begin()+i+1, nums.end());
        return ;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值