題目
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本題理解起來(lái)可能會(huì)有些困難,數(shù)組的大小要怎么比較是難點(diǎn),數(shù)組的大小就是可以看成用每一個(gè)數(shù)組成一位組成的數(shù)的大小的比較
例如 [1,23,4] > [1,4,23]
[1,23,4] 23可以看成十位,4為個(gè)位,1為百位2本題的意思是找到比當(dāng)前大的最小的數(shù)組,如果是最大的情況就找最小的
解法
首先從數(shù)組的最后面找到 nums[i] < nums[i+1] ,說(shuō)明此時(shí)的i + 1后面的數(shù)字都是遞減排序的,怎么移動(dòng)都不會(huì)使數(shù)字增大,現(xiàn)在把數(shù)字移動(dòng)到i上面,就是在后面的數(shù)字中找到最小的數(shù)字移動(dòng)。
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