LeetCode 31. 下一个排列(Next Permutation)

在这里插入图片描述

31. 下一个排列(Next Permutation)

31. 下一个排列(Next Permutation)

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

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

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

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

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

算法思路:

字典顺序生成

可以参看wiki
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order

1、先找出最大的索引(从后向前找) firstIndex 满足 nums[firstIndex] < nums[firstIndex+1],如果不存在,就翻转整个数组;
2、再在索引大于firstIndex中找出(从后向前找)第一次另一个最大索引 secondIndex 满足 nums[secondIndex ] > nums[firstIndex];
3、交换 nums[secondIndex] 和 nums[firstIndex];
4、最后翻转 索引大于firstIndex的数组 nums[firstIndex+1:]。

Python3 实现

字典顺序生成

# @author:leacoder
# @des:  按字典顺序生成 下一个排列

'''
1、先找出最大的索引 firstIndex 满足 nums[firstIndex] < nums[firstIndex+1],如果不存在,就翻转整个数组;
2、再在索引大于firstIndex中找出第一次另一个最大索引 secondIndex  满足 nums[secondIndex ] > nums[firstIndex];
3、交换 nums[secondIndex] 和 nums[firstIndex];
4、最后翻转 索引大于firstIndex的数组 nums[firstIndex+1:]。
参考:
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
'''

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        firstIndex = -1
        for i in range(n-2,-1,-1):
            if nums[i] < nums[i+1]: # 找出最大的索引 k 满足 nums[k] < nums[k+1]
                firstIndex = i
                break

        if -1 == firstIndex: # 如果不存在
            self.reverse(nums, 0, n-1)
            return
        secondIndex = -1

        # 在索引大于firstIndex中,找出secondIndex第一次使 nums[secondIndex ] > nums[firstIndex]
        for i in range(n-1,firstIndex,-1):
            if nums[i] > nums[firstIndex]:
                secondIndex = i
                break
        # 交换 nums[secondIndex] 和 nums[firstIndex];
        nums[firstIndex],nums[secondIndex] = nums[secondIndex],nums[firstIndex]
        # 翻转 索引大于firstIndex的数组 
        self.reverse(nums, firstIndex+1, n-1)
		
    # 翻转数组
    def reverse(self,nums,i,j):
        while i < j:
            nums[i],nums[j] = nums[j], nums[i]
            i += 1
            j -= 1	

GitHub链接:
https://github.com/lichangke/LeetCode
知乎个人首页:
https://www.zhihu.com/people/lichangke/
CSDN首页:
https://me.csdn.net/leacock1991
欢迎大家来一起交流学习

发布了170 篇原创文章 · 获赞 16 · 访问量 2823

猜你喜欢

转载自blog.csdn.net/leacock1991/article/details/101722569