Find the breakpoint from the end which breaks the non-increasing sequence. [1, 3, 5, 4, 2] -> 3
Traverse from end in right part and find the first element greater than breakpoint. [1, 4, 5, 3, 2] -> 34互换
Reverse the right part. [1, 4, 2, 3, 5]
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 如果第一部分用 for i in range(len(nums) -1, 0, -1)写法,会导致单元素的list为空. 且费时
i = len(nums) - 1
while i > 0:
if nums[i-1] < nums[i]:
break
i -= 1
pivot = i - 1
if pivot == -1:
nums.reverse()
return
for j in range(len(nums) - 1, pivot, -1):
if nums[j] > nums[pivot]:
nums[j], nums[pivot] = nums[pivot], nums[j]
break
# python list 可以这样局部更新
nums[pivot+1:] = reversed(nums[pivot+1:])
import functools
class Solution:
def PrintMinNumber(self, numbers):
if not numbers:
return ""
num = list(map(str, numbers))
cmp = lambda a, b: 1 if a + b > b + a else -1
num = sorted(num, key=functools.cmp_to_key(cmp))
return ''.join(num)