LeetCode 31. Next Permutation-- Python solution - math - the smallest number than the current large number of

LeetCode 31. Next Permutation-- Python solution - math - the smallest number than the current large number of

This article first appeared in my personal blog: LeetCode the Next Permutation-- 31. The Python solution - math - the smallest number than the current number of large - zhang0peter personal blog


LeetCode problem solution article categories: LeetCode problem solution essay collection
LeetCode summary of all the topics: LeetCode summary of all the topics


Topic Address: the Next Permutation - LeetCode


Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

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

This question is to see that this is a classic math problems, and statistics are based on high-frequency algorithm interview questions, Facebookparticularly fond of this title.

This question seems simple, but the difficulty is still getting bigger.

1. First consider the special circumstances, if the number is complete flashback sort, which is the biggest, so long as the return to positive sequence can be sorted minimal.

2. To achieve than the minimum number of current large number of changes in low, do not modify high.

3. If the lower part of a number of flashback is sorted and then reverse sort is not high, the swap high and low is larger than that of this number, then the lower order can be sorted.

4. This question is a further difficulty is the need to place note sorting, not the pointer references to the new array.

Python solution as follows:

class Solution:
    def nextPermutation(self, nums) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        flag = -1
        for i in range(len(nums)-2, -1, -1):
            if nums[i] < nums[i+1]:
                flag = i
                break
        if flag == -1:
            nums.sort()
        else:
            for i in range(len(nums)-1, flag, -1):
                if nums[i] > nums[flag]:
                    nums[i], nums[flag] = nums[flag], nums[i]
                    nums[flag+1:] = sorted(nums[flag+1:])
                    break

The time complexity is O (n), the spatial complexity is O (1).

Published 516 original articles · won praise 159 · views 510 000 +

Guess you like

Origin blog.csdn.net/zhangpeterx/article/details/104067476