LeetCode 31. Next Permutation-- Python 解法--數學題--比當前數大的最小的數

LeetCode 31. Next Permutation-- Python 解法–數學題–比當前數大的最小的數

此文首發於我的個人博客:LeetCode 31. Next Permutation-- Python 解法–數學題–比當前數大的最小的數 — zhang0peter的個人博客


LeetCode題解文章分類:LeetCode題解文章集合
LeetCode 所有題目總結:LeetCode 所有題目總結


題目地址: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

這道題目一看就知道是經典的數學題,而且根據統計是高頻面試算法題,Facebook尤爲喜歡這題。

這道題目看起來簡單,做起來難度還是挺大的。

1.先考慮特殊情況,如果這個數是完全倒敘排序的,也就是最大的,那麼只要返回正序排序最小的即可。

2.想要實現比當前數大的最小的數,改變低位,不要修改高位。

3.如果一個數的低位部分是倒敘排序,然後高位不是倒序排序,那麼交換高位和低位中大於它的這個數,然後把低位順序排序即可。

4.這道題目另外一個需要注意的難點是需要就地排序,不能把指針引用指向新的數組。

Python解法如下:

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

時間複雜度爲O(n),空間複雜度爲O(1)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章