leetcode 31. Next permutation (python3) 44ms

Title description:

Implement the function to get the next permutation. The algorithm needs to rearrange the given sequence of numbers into the next larger permutation in lexicographical order.
If no next larger permutation exists, rearrange the numbers into the smallest permutation (i.e. ascending order).
Must be modified in-place, only extra constant space is allowed.

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]

Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]

Example 4:

input: nums = [1]
output: [1]

Problem-solving ideas:

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if len(nums) <= 1:
            return
        target1 = -1
        for idx in range(len(nums) - 1, 0, -1):
            if nums[idx] <= nums[idx - 1]:
                continue
            else:
                target1 = idx - 1
                break
        if target1 == -1:
            nums[target1 + 1:] = nums[target1 + 1:][::-1]
            return
        for idx in range(len(nums) - 1, target1, -1):
            if nums[idx] > nums[target1]:
                nums[idx], nums[target1] = nums[target1], nums[idx]
                break
        nums[target1 + 1:] = nums[target1 + 1:][::-1]

Algorithm performance:
insert image description here

Guess you like

Origin blog.csdn.net/lanmengyiyu/article/details/109851966