31. 下一个排列

2020-02-04  本文已影响0人  oneoverzero

题目描述:

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

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

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

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

代码:

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        is_possible = False
        
        # step 1: find the first nums[i] < nums[ii] from the tail
        for i in range(len(nums)-1, 0, -1):
            if nums[i-1] < nums[i]:
                i, ii = i-1, i
                is_possible = True
                break
        
        # step 2: find the first nums[j] > nums[i] from the tail and swap nums[i], nums[j]
        if is_possible:
            for j in range(len(nums)-1, -1, -1):
                if nums[j] > nums[i]:
                    nums[i], nums[j] = nums[j], nums[i]
                    # step 3: reverse all the elements starting from ii
                    nums[ii:] = nums[ii:][::-1]
                    break
        else:
            nums[:] = nums[::-1]

什么是下一个排列以及本题的思路分析:

核心思想是:

曾出错过的地方:

上一篇 下一篇

猜你喜欢

热点阅读