输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 1:
输入: [10,2]
输出: "102"
示例 2:
输入: [3,30,34,5,9]
输出: "3033459"
提示:
0 < nums.length <= 100
说明:
输出结果可能非常大,所以你需要返回一个字符串而不是整数
拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof
这道题就是排序,不过要换一下排序规则,不是单纯比大小:
比如 x = ‘3’,y = ‘30’ ,x+y='330' y+x = '303' 因为330>303,但是我们求拼接最小的数,所以此时x和y要换位
用内置函数:
class Solution:
def minNumber(self, nums: List[int]) -> str:
from functools import cmp_to_key
def compare(a,b):
if a+b>b+a:
print(a+b)
return 1
elif a+b==b+a:
return 0
else:
return -1
strs = [str(num) for num in nums]
strs.sort(key=cmp_to_key(compare))
return ''.join(strs)
自己写排序方法:冒泡:
class Solution:
def minNumber(self, nums: List[int]) -> str:
# 冒泡排序:
lens = len(nums)
strs = [str(num) for num in nums]
for i in range(lens-1):
for j in range(lens-1-i):
if strs[j]+strs[j+1]>strs[j+1]+strs[j]:
strs[j],strs[j+1]=strs[j+1],strs[j]
return ''.join(strs)
选择排序:
class Solution:
def minNumber(self, nums: List[int]) -> str:
# 选择排序
lens = len(nums)
strs = [str(num) for num in nums]
for i in range(lens-1):
for j in range(i+1,lens):
if strs[i]+strs[j]>strs[j]+strs[i]:
strs[i],strs[j]=strs[j],strs[i]
return ''.join(strs)
插入排序:
class Solution:
def minNumber(self, nums: List[int]) -> str:
# 插入排序
lens = len(nums)
strs =[str(num) for num in nums]
for i in range(1,lens):
value = strs[i] = i
while j>=1 and v alue+strs[j-1]<strs[j-1]+value:
strs[j]=strs[ j-1]
j-=1
strs[j]=value
return ''.join(strs)
快速排序:
class Solution:
def minNumber(self, nums: List[int]) -> str:
# 快速排序
def partition(arr,l,r):
v = strs[r]
while(l<r):
while(l<r and strs[l]+v<=v+strs[l]):
l+=1
strs[r] = strs[l]
while(l<r and strs[r]+v>=v+strs[r]):
r-=1
strs[l] = strs[r]
strs[l]=v
return l
def fast_sort(arr,l,r):
if l<r:
idx = partition(arr,l,r)
fast_sort(arr,l,idx-1)
fast_sort(arr,idx+1,r)
lens = len(nums)
strs =[str(num) for num in nums]
l = 0
r = lens-1
fast_sort(strs,l,r)
return ''.join(strs)