数据结构算法操作试题(C++/Python)——下一个排列

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——下一个排列,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 题目

leetcode 链接:https://leetcode-cn.com/problems/next-permutation/

2. 解答

python:60ms, 10.7mb

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        preMax, minIndex = -1, 0
        for i in range(len(nums) - 1):
            if nums[i] < nums[i + 1]:
                preMax = i
        if preMax == -1:
            nums.reverse()
            return
        for i in range(preMax + 1, len(nums)):
            if nums[i] > nums[preMax]:
                minIndex = i
        nums[preMax], nums[minIndex] = nums[minIndex], nums[preMax]
        nums[preMax + 1:] = nums[:preMax:-1]

其他方法看 leetcode 链接 评论区~