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