题目
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
代码
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
lens = len(nums)
if lens == 2:
t = nums[0]
nums[0] = nums[1]
nums[1] = t
return
else:
x = nums[0]
low = -lens
high = -lens
#找最靠右边的需要交换的位置
for i in range(-1,-lens,-1):
for j in range(i-1,-lens-1,-1):
if nums[i] > nums[j]:
if low<j:
low = j
high = i
if low==j:
high = max(high,i)
#不存在下一个更大的排列
if low==-lens and high ==-lens:
i = 0
for x in nums[::-1]:
nums[i] = x
i += 1
return
#交换位置
t = nums[low]
nums[low] = nums[high]
nums[high] = t
#排序
temp = low+lens+1
a = sorted(nums[temp:])
nums[temp:] = a