Leetcode P31 Next Permutation @python Lang (LL)

9 篇文章 0 订阅
9 篇文章 0 订阅

Link: https://leetcode.com/problems/next-permutation/
Content:
在这里插入图片描述
Analysis:
next permutation means 仅仅比这个数大的下一个数
如果是一个降序的数,比如9876,则如何排列都没有比之更大的数,此时将数列逆序排列,即 sorted it in ascending order
从上也可知,我们可以先从后向前看,直到找到破坏降序的数,将之与仅仅比它大的数调换
eg: 12641
643为降序,这三个数无论怎样排列都无法比643大,因此在2上做文章,调一个仅仅比它大的数,为4,此时为 14621,后面三个数621为最大排序,应调为126,此时即为仅仅比原数大的数。
final result: 14126

Method:
Algorithm:

  1. traverse i the whole array, from back to front, until one number nums[i]<nums[i+1], partition = i
  2. because of the last i digits is in descending order, the last one is the smallest, j traverse from back to front, until nums[j], greater than nums[partition]. swap nums[j] and nums[partition].
  3. from partition+1 to len(nums)-1 in ascending order.

Code:

def nextpermutation(nums):
    if len(nums) <= 1:
        return nums
    partition = -1
    for i in range(len(nums)-2, -1, -1):
        if nums[i] < nums[i+1]:
            partition = i
            break
    if partition == -1:
        nums.reverse()
        return nums
    else:
        for j in range(len(nums)-1, partition, -1):
            if nums[j] > nums[partition]:
                nums[j], nums[partition] = nums[partition], nums[j]
                break
    left = partition + 1
    right = len(nums) - 1
    while left < right:
        nums[left], nums[right] = nums[right], nums[left]
        left += 1
        right -= 1
    return nums

Attention:
break 用法 until… 还有注意各个block之间的关系

Time complexity:
O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值