31. 下一个排列

题目:

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

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

31. 下一个排列

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

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

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

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

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

思路:

参考:https://www.nayuki.io/page/next-lexicographical-permutation-algorithm

代码:

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        i, j = len(nums)-1, len(nums)-1
        while j > 0 and nums[j-1] >= nums[j]:
            j -= 1
        if j == 0:
            nums.reverse()
            return

        k = j-1
        while nums[i] <= nums[k]:
            i -= 1
        nums[i], nums[k] = nums[k], nums[i]

        l, r = j, len(nums)-1
        while l < r:
            nums[l], nums[r] = nums[r], nums[l]
            l += 1
            r -= 1

import "sort"

func nextPermutation(nums []int) {
    i, j := len(nums)-1, len(nums)-1
    for j > 0 && nums[j-1] >= nums[j] {
        j--
    }
    if j == 0 {
        sort.Ints(nums)
        return
    }
    for i > 0 && nums[j-1] >= nums[i] {
        i--
    }

    nums[j-1], nums[i] = nums[i], nums[j-1]
    l, r := j, len(nums)-1
    for l < r {
        nums[l], nums[r] = nums[r], nums[l]
        l++
        r--
    }
}

你可能感兴趣的:(31. 下一个排列)