题目描述
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). The replacement must be in place and use only constant extra memory.
解题思路
这道题应该属于一道规律技巧题,难度在于寻找规律. 我认为这道题的规律是: 变尾不变前,看代码:
代码
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) == 1:
return nums
if nums[len(nums) - 1] > nums[len(nums) - 2]:
temp = nums[len(nums) - 1]
nums[len(nums) - 1] = nums[len(nums) - 2]
nums[len(nums) - 2] = temp
return nums
cur = nums[len(nums) - 1]
flag = 0
for i in range(len(nums) - 2, -1, -1):
if nums[i] < cur:
flag = 1
break
else:
cur = nums[i]
if flag:
for j in range(i + 1, len(nums)):
if nums[j] > nums[i]:
if j == len(nums) - 1 or nums[j + 1] <= nums[i]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
for j in range(i + 1, (len(nums) + i + 1) // 2):
temp = nums[j]
nums[j] = nums[len(nums) + i - j]
nums[len(nums) + i - j] = temp
else:
for j in range(len(nums) // 2):
temp = nums[j]
nums[j] = nums[len(nums) - j - 1]
nums[len(nums) - j - 1] = temp