LeetCode---31. Next Permutation

题目

给出一个序列,按照字典序重新安排序列元素的顺序,使得新的序列是下一个比原来序列大。如果不存在,就将序列逆序。

Python题解

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        i = len(nums) - 2
        while i >= 0 and nums[i + 1] <= nums[i]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while j > 0 and nums[j] <= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]
        self.reverse(nums, i + 1)
        return nums

    def reverse(self, nums, start):
        low, high = start, len(nums) - 1
        while low < high:
            nums[low], nums[high] = nums[high], nums[low]
            low += 1
            high -= 1

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80482064