• 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, do not allocate 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的题目,题目要求inplace,所以很明显,类似于permutation那种全部求出结果再查找的方法肯定不行,只有真正找到词典序的规律。记得之前组合数学课上曾经学过这种,当时怎么都没想明白书中给的方法,没想到这题结合举例分析,竟然想出了和书中方法完全一样的解法,甚为开心呐~

    总体思路如下:

    1.从前向后找一个严格递增的子序列,将递增子序列的最后一个i记为up。

    2.因为up及之后的数字组成了一个非递增序列,所以改变后面的数字排序不能得到下一个更大的数字。所以需要修改的是up-1这个位上的数,即nums[up:]中比nums[up-1]大的最小值,也即将其修改为nums[up:]中最后一个比其大的数字,(因为是非递增序列)。找到这个index,交换nums[index],nums[up-1]

    3.将nums[up:]逆序,其实是做一次升序排序,但是考虑交换nums[index],nums[up-1]后,nums[up:]依然为非递增序列,所以只要reverse就可以。

    举个例子,7 2 5 3 3 1。先找到 up为2,则nums[up-1]为2,nums[up:] 中比2大的最小值为3,注意是取最后一个3,方便第3步直接reverse,获得增序排序。

    交换数字之后成为 7 3 5 3 2 1,然后对5321做一个逆序,获得最终的排序为7 3 1 2 3 5。

    可以看到最多扫描三次, up 为0时,直接reverse,扫描两次。空间复杂度为O(1),代码如下:

    class Solution(object):
        def nextPermutation(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            up = 0
            for i in xrange(1,len(nums)):
                if nums[i] > nums[i-1]:
                    up = i
            if up == 0:
                nums.reverse()
            else:
                index = up
                for i in xrange(up,len(nums)):
                   if nums[i] >  nums[up-1]:
                       index = i
                nums[up-1], nums[index] = nums[index], nums[up-1]
                for i in xrange((len(nums) - up)/2):
                    nums[up + i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[up+i]
  • 相关阅读:
    openjudge 2750
    hexo部署云服务器
    freemaker传输数据问题
    FormData在axios中的骚操作
    Docker安装与初次使用
    docker-compose实现前后端分离的自动化部署
    centos7下设置静态ip
    centos7 安装mariadb 并配置主从复制
    centos7安装solr服务
    centos7安装redis
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5568452.html
Copyright © 2020-2023  润新知