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 and use only constant 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
这道题要求字典序的下一个元素,permutation是排列的意思。字典序是这样的,假如我们要排列1,2,3这三个数,它们的全排列:
[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1]
按这种顺序排列,也就是从小到大排列。从中可以看到规律,下一个元素比上一个元素大一点,然后再下一个再大一点。所以这道题是要找出比当前排列大的排列中的最小数。
排列的方法为:从后向前遍历,找出第一个不满足比它后一个数大的数,然后将这个数与其后面的数列中比该数大的最小数交换,最后将后面的数列逆序。
以[6,5,4,8,7,5,1]为例,从后向前遍历,找到第一个不满足递增的数:4 然后找出刚好比4大一点的数:5 交换4和5,此时数列为
[6,5,5,8,7,4,1],最后将原4位置后面的数列逆序,[6,5,5,1,4,8,7]
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1)[::-1]:
if nums[i]<nums[i+1]:
for j in range(len(nums))[::-1]:
if nums[i]<nums[j]:
tmp=nums[i]
nums[i]=nums[j]
nums[j]=tmp
nums[i+1:]=nums[i+1:][::-1]
return
nums.reverse()