[Leetcode]31. Next Permutation

  • 本題難度: Medium
  • Topic: Greedy

Description

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.html

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).python

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.code

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

別人的代碼

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不同,這一沒有返回值,直接改變原數組。blog

相關文章
相關標籤/搜索