LeetCode Next Permutation

LeetCode解题之Next Permutation


原题

找出一个数组按字典序排列的后一种排列。python

注意点:git

  • 假设原来就是字典序排列中最大的。将其又一次排列为字典序最小的排列
  • 不要申请额外的空间
  • 当心数组越界问题
  • 函数没有返回值,直接改动列表

样例:github

输入: [1,2,3]
输出: [1,3,2]数组

输入: [3,2,1]
输出: [1,2,3]markdown

解题思路

经过一个样例来讲明,原数组为[1,7,3,4,1]。咱们想要找到比173421大一点的数,那就要优先考虑将后面的数字变换顺序。而421从后往前是升序的(也就是这三个数字能组成的最大的数),变换了反而会变小,因此要先找到降序的点。可以看出3是第一个降序的点,要想整个数变大,3就要变大。从后往前找到第一个比3大的数4,将3和4交换位置获得174321,既然原来3所在位置的数字变大了,那整个数确定变大了。而它以后的数是最大的(从后往前是升序的),应转换成最小的,直接翻转。函数

AC源代码

class Solution(object):
    def nextPermutation(self, nums):
        """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """
        length = len(nums)

        targetIndex = 0
        changeIndex = 0
        for i in range(length - 1, 0, -1):
            if nums[i] > nums[i - 1]:
                targetIndex = i - 1
                break
        for i in range(length - 1, -1, -1):
            if nums[i] > nums[targetIndex]:
                changeIndex = i
                break
        nums[targetIndex], nums[changeIndex] = nums[changeIndex], nums[targetIndex]
        if targetIndex == changeIndex == 0:
            nums.reverse()
        else:
            nums[targetIndex + 1:] = reversed(nums[targetIndex + 1:])

欢迎查看个人Github (https://github.com/gavinfish/LeetCode-Python) 来得到相关源代码。post

相关文章
相关标签/搜索