题目
解决方法
参看官方解决思路,就是将数列中的元素两两拼接。如’2’+‘3’=‘23’<‘3’+‘2’='32’则2在3的左边。由于该题不用考虑组合后第一位是零的情况,所以这样将所有的元素比较排序后直接拼接为str即可。
官方给出的解决代码
class Solution(object):
def minNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def quick_sort(l , r):
if l >= r: return
i, j = l, r
while i < j:
while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1
while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1
strs[i], strs[j] = strs[j], strs[i]
strs[i], strs[l] = strs[l], strs[i]
quick_sort(l, i - 1)
quick_sort(i + 1, r)
strs = [str(num) for num in nums]
quick_sort(0, len(strs) - 1)
return ''.join(strs)
评论区代码
class Solution(object):
def minNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
n=len(nums)
if n==0:
return ""
for i in range(n):
nums[i]=str(nums[i])
for i in range(n):
for j in range(i+1,n):
if nums[i]+nums[j]>nums[j]+nums[i]:
nums[i],nums[j]=nums[j],nums[i]
return "".join(nums)
直接调用python内置函数
class Solution(object):
def minNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
nums1=map(str,nums)
new_nums=sorted(nums1,key=cmp_to_key(lambda x,y:int(x+y)-int(y+x)),reverse=False)
return ''.join([str(num) for num in new_nums])