第一种做法
- 长度不一的时候,用短的元素的前缀填补到短元素的后面,然后比较;
- 若一直相等,做相加的数值比较;
from functools import cmp_to_key
#letterlist.sort(key=cmp_to_key(keyL))
class Solution(object):
def printMinNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def func(x, y):
if len(x) > len(y):
t = y[:] + y[:len(x) - len(y)]
for i, j in zip(x, t):
if i > j:
return 1
elif i < j:
return -1
xt, tx = int(x + y), int(y + x)
if xt > tx:
return 1
elif xt < tx:
return -1
return 0
elif len(x) <= len(y):
t = x[:] + x[:len(y) - len(x)]
for i, j in zip(t, y):
if i > j:
return 1
elif i < j:
return -1
ty, yt = int(x + y), int(y + x)
if ty > yt:
return 1
elif ty < yt:
return -1
return 0
nums = sorted(list(map(str,nums)), key = cmp_to_key(func))
return "".join(map(str, nums))
优化第一种方法直接拼接进行比较
from functools import cmp_to_key
class Solution(object):
def printMinNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def func(x, y):
t, g = x + y, y + x
for i, j in zip(t, g):
if i > j:
return 1
elif i < j:
return -1
return 0
nums = sorted(list(map(str,nums)), key = cmp_to_key(func))
return "".join(map(str, nums))