31.Next Permutation

2017-08-05  本文已影响0人  l_b_n

题目

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

解法

首先从数组的最后面找到 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       
上一篇 下一篇

猜你喜欢

热点阅读