leetcode31下一个更大的排列

题目: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,3—1,3,2,1,2,3,4,2,3,1–1,2,3,4,3,1,2通过观察我们知道只要找到一个位置,该位置的右侧存在一个比它大的数字,然后将这两个数字交换就可以使得列表的排列变大,那么如何保证变大的排列是最小的呢?只要我们保证这个位置尽量靠右,也就是第一个出现这种情况的位置,即从右面开始破坏升序排列的第一个位置,然后从右面找出比这个位置大的数字的最小值,进行交换,再讲右面剩下的位置逆序操作(因为右面开始的排列是一个降序排列,逆序操作可以使得排列为最小值)就可以得到我们需要的下一个更大的排列。具体实现代码如下:

def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = j = len(nums)-1
        while i > 0 and nums[i-1] >= nums[i]:
            i -= 1
        if i == 0:   
            nums.reverse()
            return 
        k = i - 1   
        while nums[j] <= nums[k]:
            j -= 1
        nums[k], nums[j] = nums[j], nums[k]  
        l, r = k+1, len(nums)-1  
        while l < r:
            nums[l], nums[r] = nums[r], nums[l]
            l +=1 ; r -= 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值