[Leetcode]31. Next Permutation

Posted siriusli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode]31. Next Permutation相关的知识,希望对你有一定的参考价值。

  • 本题难度: Medium
  • Topic: Greedy

Description

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.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

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: void Do not return anything, modify nums in-place instead.
        """
        # find longest non-increasing suffix
        right = len(nums)-1
        while nums[right] <= nums[right-1] and right-1 >=0:
            right -= 1
        if right == 0:
            return self.reverse(nums,0,len(nums)-1)
        # find pivot
        pivot = right-1
        successor = 0
        # find rightmost succesor
        for i in range(len(nums)-1,pivot,-1):
            if nums[i] > nums[pivot]:
                successor = i
                break
        # swap pivot and successor
        nums[pivot],nums[successor] = nums[successor],nums[pivot]  
        # reverse suffix
        self.reverse(nums,pivot+1,len(nums)-1)
        
    def reverse(self,nums,l,r):
        while l < r:
            nums[l],nums[r] = nums[r],nums[l]
            l += 1
            r -= 1

思路

52. Next Permutation不一样,这一没有返回值,直接改变原数组。

以上是关于[Leetcode]31. Next Permutation的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 31. Next Permutation

[array] leetcode - 31. Next Permutation - Medium

[LeetCode] 31. Next Permutation ☆☆☆

Leetcode 31. Next Permutation

LeetCode-31-Next Permutation

[Leetcode]31. Next Permutation