【Leetcode】31. Next Permutation

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.

class Solution(object):

    def nextPermutation(self, nums):

        """

        :type nums: List[int]

        :rtype: void Do not return anything, modify nums in-place instead.

        """

        if not nums: return None

        i = len(nums)-1

        j = -1

        while i>0:

            if nums[i-1]<nums[i]:

                j= i-1

                break

            i -= 1

        for i in range(len(nums)-1, -1, -1):

            if nums[i]>nums[j]:

                nums[i], nums[j]=nums[j], nums[i]

                nums[j+1:]=sorted(nums[j+1:])

                break

1 基本思路是,从后往前看,找上升的子序列,直到某一个数突然变小了,然后在这个数的后边找比它大的数中最小的那个,交换它们两个,交换后,再倒置一下后面的序列,即得到next permutation

2 从后往前找,找到第一个数字下降的地方,记录下这个位置,然后再回去从后往前找,找第一个比这个数大的数,swap它们两个,然后后面的再按升序排列

3 注意j要初始化为-1,代表特殊情况,原始序列全部是降序排列,它的next permutation是全部升序

4 在while循环里,如果nums[i-1]一直大于nums [i],则j是不会有更新的,这就是全部降序,这种情况下j=-1

5 在交换元素后,sort后部分后,就需要跳出for循环

6 注意此处需要用sorted函数而不是str.sort()函数,sorted函数可以产生一个copy



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,213评论 0 3
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 姓名:宋潇~公司:广汉油脂 【日精进打卡第26天】 【知~学习】 《六项精进》0遍 共6遍 《大学》0遍 共20遍...
    宋潇同学阅读 192评论 0 0
  • 晚 荷芦苇丛边鸣啾啾,一枝红荷待晚秋。芳草渡里寻它去,问道南山路不休。 注:芳草渡:地方名问道南山:探寻生活真谛的道路
    东原郡人阅读 306评论 3 3
  • 今天上午民族中学全体社会教师对邱老师在民族上的两节课再次认真探讨。 《统一的多民族的国家》 环节一:统一是什么? ...
    如肃阅读 211评论 0 1