A next arrangement leetcode31_

Achieve a function of the acquired arrangement, a given algorithm requires rearranging the sequence number next in lexicographically larger arrangement. If the next larger arrangement does not exist, the smallest number of rearranged alignment (i.e., ascending order). You must place editing, allowing only constant additional space.

The following are some examples, the input column on the left, on the right column the corresponding output.
→ 1, 3,2, 2, 3
3,2,1 →, 2, 3
1,1,5 1,5,1 →

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        down_index = None
        # 第一步,从后往前,找到下降点
        for i in range(n-2, -1, -1):
            if nums[i+1] > nums[i]:
                down_index = i
                break
        if down_index is not None:
            # 第二步,从后往前,找到比下降点大的数,对换位置
            for j in range(n-1, down_index, -1):
                if nums[j] > nums[down_index]:
                    self.swap(nums, down_index, j)
                    break
            # 第三部,下降点之后的数都是递减的,颠倒排序下降点之后的数
            self.reverse(nums, down_index+1)
        else:
            # 如果没有下降点,说明数组是递减的,全部颠倒排列
            self.reverse(nums, 0)

    def swap(self, nums, i, j):
        nums[i], nums[j] = nums[j], nums[i]

    # 这个是对数组进行翻转的标准方法
    def reverse(self, nums, start_position):
        i, j = start_position, len(nums)-1
        while i < j:
            self.swap(nums, i, j)
            i += 1
            j -= 1
Published 31 original articles · won praise 18 · views 6023

Guess you like

Origin blog.csdn.net/weixin_40027284/article/details/104758393