每天(?)一道Leetcode(5) Next Permutation

Array

031. 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 and use only constant extra memory.

即:
给定一个数据排列,要求找出该组数据组成的下一个比原排列大的数据,如果这样的数据不存在(原排列已经是最大组合),则将数据按升序排列(最小组合)
有点儿抽象,举个栗子
给定,从后往前找到第一个逆序位置(1-2-4-5顺序,1-2-4-5-2,出现了第一个逆序),那么将5-4-2-1中比2大的最小的数和2互换,即和4换得到4-5-2-2-1,然后将转折点5后面的子列升序排列。
这样就得到了下一个比原序列大的数据
实现如下

class Solution:
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k = -1
        for i in range(len(nums)-2,-1,-1):
            if nums[i]nums[k]:
                    nums[k],nums[i] = nums[i],nums[k]
                    break
            nums[k+1:]=sorted(nums[k+1:])

但上面的代码用了sorted和取反运算~,运行速度较慢

你可能感兴趣的:(每天(?)一道Leetcode(5) Next Permutation)