题目: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
最终被接受的代码如下:
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
len_num=len(nums)
if len_num>=2:
blag=0
for j in range(len_num-2,-1,-1):
for i in range(len_num-1,j,-1):
if nums[i]>nums[j]:
blag=1
nums[i],nums[j]=nums[j],nums[i]
tmp=nums[j+1:]
tmp.sort()
nums[j+1:]=tmp
break
if blag==1:
break
else:
nums.reverse()
注意一下几点:
1.在python3中,虽然对列表进行切片后的结果仍为列表,但好像无法调用List类型对应的内置方法。
>>> a
[1, 2, 3, 4, 5]
>>> a[1:].reverse()
>>> a
[1, 2, 3, 4, 5]
>>>
所以这里定义了一个中间变量tmp,辅助更改列表。(至于为什么会出现这种情况,原因不明)
2.这个题目实际是寻找一个由列表中的与元素组成的数字中所有比现有数字大的最小数字。所以这里要注意两层for循环中,i和j谁做外循环,谁做内循环。刚开始我就是没有注意到这个问题,所以提交之后一直报错。