Leetcode 31. Next Permutation

本文介绍如何实现寻找数组中字典序下一个更大排列的算法。通过从后向前查找不满足递增条件的元素,并与后序中大于该元素的最小值进行交换,最后对交换后的位置进行逆序操作。

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

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 and use only constant 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

这道题要求字典序的下一个元素,permutation是排列的意思。字典序是这样的,假如我们要排列1,2,3这三个数,它们的全排列:

[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1]

按这种顺序排列,也就是从小到大排列。从中可以看到规律,下一个元素比上一个元素大一点,然后再下一个再大一点。所以这道题是要找出比当前排列大的排列中的最小数。

排列的方法为:从后向前遍历,找出第一个不满足比它后一个数大的数,然后将这个数与其后面的数列中比该数大的最小数交换,最后将后面的数列逆序。

以[6,5,4,8,7,5,1]为例,从后向前遍历,找到第一个不满足递增的数:4 然后找出刚好比4大一点的数:5 交换4和5,此时数列为

[6,5,5,8,7,4,1],最后将原4位置后面的数列逆序,[6,5,5,1,4,8,7]

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)-1)[::-1]:
            if nums[i]<nums[i+1]:
                for j in range(len(nums))[::-1]:
                    if nums[i]<nums[j]:
                        tmp=nums[i]
                        nums[i]=nums[j]
                        nums[j]=tmp
                        nums[i+1:]=nums[i+1:][::-1]
                        return
        nums.reverse()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值