31. Next Permutation

https://leetcode.com/problems/next-permutation/

solution

  • Find the breakpoint from the end which breaks the non-increasing sequence. [1, 3, 5, 4, 2] -> 3

  • Traverse from end in right part and find the first element greater than breakpoint. [1, 4, 5, 3, 2] -> 34互换

  • Reverse the right part. [1, 4, 2, 3, 5]

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # 如果第一部分用 for i in range(len(nums) -1, 0, -1)写法,会导致单元素的list为空. 且费时
        i = len(nums) - 1
        while i > 0:
            if nums[i-1] < nums[i]:
                break
            i -= 1

        pivot = i - 1
        if pivot == -1:
            nums.reverse()
            return

        for j in range(len(nums) - 1, pivot, -1):
            if nums[j] > nums[pivot]:
                nums[j], nums[pivot] = nums[pivot], nums[j]
                break

        # python list 可以这样局部更新
        nums[pivot+1:] = reversed(nums[pivot+1:])

时间复杂度:O(n) 空间复杂度:O(1)

follow up - 多步翻转法

189. Rotate Array

  • in-place

179. Largest Number

剑指Offer 45: 把数组排成最小的数

186 Reverse Words in a String II

24. Swap Nodes in Pairs

556. Next Greater Element III

Last updated