31.Next Permutation

题目

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, do not allocate 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

  • 1本题理解起来可能会有些困难,数组的大小要怎么比较是难点,数组的大小就是可以看成用每一个数组成一位组成的数的大小的比较
    例如 [1,23,4] > [1,4,23]
    [1,23,4] 23可以看成十位,4为个位,1为百位

  • 2本题的意思是找到比当前大的最小的数组,如果是最大的情况就找最小的

解法

首先从数组的最后面找到 nums[i] < nums[i+1] ,说明此时的i + 1后面的数字都是递减排序的,怎么移动都不会使数字增大,现在把数字移动到i上面,就是在后面的数字中找到最小的数字移动。

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        size = len(nums)
        i = size - 2
        while i >= 0:
            if nums[i] < nums[i + 1]:
                j = i + 1
                while j < size:
                    if nums[i] >= nums[j]:
                        break
                    j += 1
                j -= 1
                nums[i],nums[j] = nums[j],nums[i]
                nums[i + 1:] = sorted(nums[i + 1:])
                return
            i -= 1
        k = 0
        middle = (size - 1) // 2
        while k <= middle:
            nums[k],nums[size - 1 - k] = nums[size - 1 - k],nums[k]
            k += 1
        return       
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容