思路,
- 從后(倒數(shù)第二位開(kāi)始)往前找到第一個(gè)比后面相鄰一位小的index,設(shè)置為target;
- 如果target==-1(數(shù)組的元素是按照從大到小排列晰赞,則直接將數(shù)組排序后輸出);
- 從target開(kāi)始往后遍歷选侨,找到和當(dāng)前target大掖鱼,但最接近的數(shù)字對(duì)應(yīng)的index為replace;
- 交換target和replace的數(shù)字所在位置援制;
- 將target后面的數(shù)組從小到大排序戏挡。
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
idx = len(nums) - 2
target = -1
for i in range(idx, -1, -1):
if nums[i] > nums[i + 1]:
continue
else:
target = i
break
if target == -1:
return sorted(nums)
replace = len(nums) - 1
for i in range(target + 1, len(nums)):
if nums[i] <= nums[target]:
replace = i - 1
break
nums[target], nums[replace] = nums[replace], nums[target]
res = nums[:target + 1]
res.extend(sorted(nums[target + 1:]))
return res