题解1:两次排序
def fn(nums):
# 根据首位先排序
s = list(map(str, nums))
ordered = sorted(s, key=lambda x:str(x), reverse=True)
# 首位相同的,进行二次排序
for i in range(len(ordered)-1):
if ordered[i][0] == ordered[i+1][0]:
if int(ordered[i][-1]) < int(ordered[i+1][0]):
ordered[i], ordered[i+1] = ordered[i+1], ordered[i]
return ''.join(ordered)
assert fn([30,1]) == "301"
assert fn([1, 201, 20, 9, 8]) == "98202011"
assert fn([1, 203, 20, 9, 8]) == "98203201"
题解2:穷举
import itertools
def fn(nums):
pertmute = list(itertools.permutations([str(x) for x in nums], len(nums)))
result = list(map(lambda x:''.join(x), pertmute))
return max(result)
assert fn([30,1]) == "301"
assert fn([1, 201, 20, 9, 8]) == "98202011"
assert fn([1, 203, 20, 9, 8]) == "98203201"
题解3:分治
import itertools
def fn(nums):
total = []
for i in range(10)[::-1]:
data = list(filter(lambda x:str(x).startswith(str(i)), nums))
if data:
if len(data) > 1:
p = list(itertools.permutations(data, len(data)))
total.append([max([str(x)+str(y) for x,y in p])])
else:
total.append(data)
return ''.join([str(x[0]) for x in total])
assert fn([30,1]) == "301"
assert fn([1, 201, 20, 9, 8]) == "98202011"
assert fn([1, 203, 20, 9, 8]) == "98203201"