LeetCode算法题之31. Next Permutation(medium)

题目描述:

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

题目大意:

  • 给定一个数组列表,要求在原地修改数组,使修改后数组组成的数字比之前的数字,按照升序的顺序,大的最少,如何理解,看例子,一看便知

解题思路:

  • 给大家上一张来源于官网解法的动图,非常清晰,非常巧妙,供各位学习
    在这里插入图片描述
  • 第一步:从后向前,依次遍历数组,直到找出开始降序的那一个数,记为a,因为题中要求,排列后的新数组只能比之前的,大一个等级,所以只有当原数组中的数有开始下降的趋势时,才有可能使其变大,如果一直上升,那么那个数一定是最大
  • 第二步:找到a后,再从a开始,向后遍历,再找出比a只大一个等级的数b,因为未必存在比a大1的数,所以去找比a大,但大的最少的数b
  • 第三步:交换a,b的数值
  • 第四步:这样还不算完,这也不符合题目要求,还要在a之后的数组中,按照升序排列,这样修改后的数组,才是题目要求
  • 还有最后一点要注意,依题目要求,不要有任何返回值,直接原地在数组中上修改

少废话,上代码:

class Solution:
    def nextPermutation(self, nums):
        """
        Do not return anything, modify nums in-place instead.
        """
        #首先判断一种特殊情况,按题目要求,如果此时排列是最大
        #则返回顺序排列的原数组
        if nums == sorted(nums, reverse=True):
            nums_s = sorted(nums)
            for i in range(len(nums)):
                nums[i] = nums_s[i]
 
        #其余一般情况
        else:
            #1.找出开始下降的那个数的索引,记为m
            for i in range(len(nums)-1, 0, -1):
                if nums[i-1] < nums[i]:
                    m = i - 1
                    break
            #2.找出那个数后面的只比他大一点点,也就是差值最小的那个数的索引
            n = m + 1#假定就是后面的那一个数
            a = nums[i] - nums[m]#初始化一个差值
            for i in range(m+1, len(nums)):
                if nums[i] - nums[m] < a and nums[i] - nums[m] > 0:
                    a = nums[i] - nums[m]#更新a的值
                    n = i#更新索引值
            #3.交换数值
            b = nums[n]
            nums[n] = nums[m]
            nums[m] = b
            #4.将交换后的数值,后面的数按照升序排列,符合题目要求
            j = 0
            nums_s = sorted(nums[m+1:len(nums)])
            for i in range(m+1, len(nums)):
                nums[i] = nums_s[j]
                j += 1

时间空间复杂度:

  • Runtime: 40 ms, faster than 67.71% of Python3 online submissions for Next Permutation.
  • Memory Usage: 13.9 MB, less than 5.56% of Python3 online submissions for Next Permutation
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值