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
改变数字排序,找到这些数字组成的下一个更大的数。如果当前数字已经是最大的数字,则返回最小的数字。
这道题想好怎么转换即可。
如果整个字符串都是升序排列,比如[1,2,4],则这个数字一定是三个数字所有组成方式最小的,只需要改变最后两个数字位置即可[1,4,2]。
如果整个字符串都是降序排列,比如[4,2,1],则一定是最大的数字,倒序即可得到答案[1,2,4]。
一个普通的字符串,比如[1,2,4,3,1],它应该得到的结果是[1,3,1,2,4]
方法就是从后到前,找到第一个不是升序排列的数字,这里是2,然后找到它后面字符串中刚刚比它大的数字,这里是3,交换顺序,变为[1,3,4,2,1],然后将这个数字后面的数字[4,2,1]倒置,最后就变为了[1,3,1,2,4]。
具体做法见代码。这里我将最后加了个-1是防止在找刚刚比非升序大的数字的时候出错。
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
maxx=float('-inf')
for i in range(len(nums)-1,-1,-1):
if nums[i]>maxx:
maxx=nums[i]
elif nums[i]<maxx:
nums+=[-1]
for j in range(i+2,len(nums)):
if nums[j]<=nums[i]:
nums[i],nums[j-1]=nums[j-1],nums[i]
break
nums[i+1:]=nums[len(nums)-1:i:-1]
nums.remove(-1)
return nums
return nums.reverse()