美文网首页leetcode
31. 下一个排列

31. 下一个排列

作者: 十月里的男艺术家 | 来源:发表于2020-02-25 08:45 被阅读0次

题目:

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--
    }
}

相关文章

  • LeetCode-31-下一个排列

    LeetCode-31-下一个排列 31. 下一个排列[https://leetcode-cn.com/probl...

  • LeetCode 31. 下一个排列 | Python

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

  • 31. 下一个排列

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

  • 全排列问题偷鸡做法

    全排列问题偷鸡摸狗做法用强大的(猥琐的)next_permutation 31. 下一个排列 46. 全排列 47...

  • 每日一题20201118(31. 下一个排列)

    31. 下一个排列[https://leetcode-cn.com/problems/next-permutati...

  • LeetCode每日一题: 31. 下一个排列

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

  • 【LeetCode】排列问题

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

  • 31. 下一个排列

    31. 下一个排列 题目链接:https://leetcode-cn.com/problems/next-perm...

  • LeetCode-31 下一个排列

    题目:31. 下一个排列 难度:中等 分类:数组 解决方案:数组遍历 今天我们学习第31题下一个排列,这是一个中等...

  • ARTS打卡第六周

    ARTS打卡第六周 Algorithm:每周至少做一个 leetcode 的算法题 31. 下一个排列 代码: 官...

网友评论

    本文标题:31. 下一个排列

    本文链接:https://www.haomeiwen.com/subject/uzczqhtx.html