Leetcode031 next-permutation

下一个排列

题目描述:

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1


解题思路:

  • 首先先找到从尾部升序结束的点,因为这个点使我们需要修改的位置
  • 然后判断这个位置是不是这个数值的第一个位置,如果是,意味着这是数值是最大的,则直接进行sort()排序
  • 从后往前找第一个大于该位置j点的值
  • 然后进行交换,同时获得从小到大排序后j点之后的数值数组a
  • 将数组a的值插入到j点之后即可

Python源码:

class Solution:
    def nextPermutation(self, nums: 'List[int]') -> 'None':
        """
        Do not return anything, modify nums in-place instead.
        """
        i = len(nums) - 1
        if len(list(set(nums))) != 1:
            
            #先从尾部升序结束的点
            while i - 1 >= 0:
                if nums[i] <= nums[i - 1]:
                    i = i - 1
                else:
                    break
            #如果前面还有至少一个位置
            if i - 1 >= 0:
                j = i - 1
 
                t = len(nums) - 1
                #从后往前找第一个大于j位置上的数
                while nums[t] <= nums[j]:
                    t -= 1
                nums[t], nums[j] = nums[j], nums[t]
                a = sorted(nums[i:])
                a_index = 0
                #以下是对nums的排序
                for index in range(i, len(nums)):
                    nums[index] = a[a_index]
                    a_index += 1
            #没有位置则sort
            else:
                nums.sort()

欢迎关注我的github:https://github.com/UESTCYangHR

你可能感兴趣的:(Leetcode031 next-permutation)