Next Permutation

问题:给定一个数组,输出对该数组排序时只比当前数组大一级的数组,如果没有,则输出从低到高的排序数组

示例:

输入:[1,2,3] 输出:[1,3,2]

输入:[3,2,1] 输出:[1,2,3]

输入:[5,5,7] 输出:[5,7,5]

解决思路:从右到左,固定某个位置,从右到该位置之前的一个位置进行遍历,如果数组元素大于固定的位置,则进行交换,之后对该位置右边的元素进行排序。如果最终没有发生交换,则将数组翻转。

Python代码:

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        flag = False
        if length == 1:
            return
        i = length - 2
        while i >= 0:
            j = length - 1
            while j > i:
                if nums[i] < nums[j]:
                    nums[i],nums[j] = nums[j],nums[i]
                    flag = True
                    # Sort elements after nums[i]
                    if length-i-1 >= 2:
                        for n in range(i+1,length-1):
                            fl = True
                            for m in range(i+1,length-n+i):
                                if nums[m] > nums[m+1]:
                                    nums[m],nums[m+1] = nums[m+1],nums[m]
                                    fl = False
                            if fl:
                                break
                    return 
                j -= 1
            i -= 1
        if not flag:
            nums.reverse()
                    
原文地址:https://www.cnblogs.com/wenqinchao/p/10709939.html