31.下一个排列

找下一个排列,也就是从后往前遍历,然后从这个元素往后遍历找到比他大的 元素中最小的元素,跟当前元素交换,然后剩下的元素排序。 没符合题目中要求只使用额外常数空间的要求

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        t = nums[::]
        for i in range(len(nums)-1, -1, -1):
            min_val = None
            index = None
            for j in range(i+1, len(nums)):
                if nums[j] <= nums[i]:
                    continue
                if min_val is None or nums[j] < min_val:
                    min_val = nums[j]
                    index = j
            if  index is not None:
                t[i], t[index] = t[index], t[i]
                t = t[:i+1] + list(sorted(t[i+1:]))
                for ii in range(len(t)):
                    nums[ii] = t[ii]
                return
        t = nums[::-1]
        for ii in range(len(t)):
            nums[ii] = t[ii]

评论