LeetCode31. Next Permutation(思路及python解法)

173 篇文章 0 订阅

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


改变数字排序,找到这些数字组成的下一个更大的数。如果当前数字已经是最大的数字,则返回最小的数字。

这道题想好怎么转换即可。

如果整个字符串都是升序排列,比如[1,2,4],则这个数字一定是三个数字所有组成方式最小的,只需要改变最后两个数字位置即可[1,4,2]。

如果整个字符串都是降序排列,比如[4,2,1],则一定是最大的数字,倒序即可得到答案[1,2,4]。

一个普通的字符串,比如[1,2,4,3,1],它应该得到的结果是[1,3,1,2,4]

方法就是从后到前,找到第一个不是升序排列的数字,这里是2,然后找到它后面字符串中刚刚比它大的数字,这里是3,交换顺序,变为[1,3,4,2,1],然后将这个数字后面的数字[4,2,1]倒置,最后就变为了[1,3,1,2,4]。

具体做法见代码。这里我将最后加了个-1是防止在找刚刚比非升序大的数字的时候出错。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值