美文网首页
31.Next Permutation

31.Next Permutation

作者: l_b_n | 来源:发表于2017-08-05 21:04 被阅读0次

    题目

    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       
    

    相关文章

      网友评论

          本文标题:31.Next Permutation

          本文链接:https://www.haomeiwen.com/subject/fejwlxtx.html