输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323
if __name__ == '__main__':
# numbers = [3, 32, 321]
# def compare( num1, num2):
# t = str(num1) + str(num2)
# s = str(num2) + str(num1)
# if t > s:
# return 1
# elif t < s:
# return -1
# else:
# return 0
# #相当于冒泡排序
# stringlist=[]
# for num in numbers:
# stringlist.append(str(num))
# slen=len(numbers)
# for i in range(slen-1):
# for j in range(i,slen):
# if compare(stringlist[i],stringlist[j])==1:
# stringlist[i],stringlist[j]=stringlist[j],stringlist[i]
# print("".join(stringlist))
#归并排序处理
def merge_sort(numbers):
strNum = [str(i) for i in numbers]
n = len(numbers)
mid = n // 2
if n == 0:
return
if n == 1:
return strNum
left_list = merge_sort(numbers[:mid])
right_list = merge_sort(numbers[mid:])
result = []
left_pointer, right_pointer = 0, 0
while left_pointer < len(left_list) and right_pointer < len(right_list):
if left_list[left_pointer] + right_list[right_pointer] > right_list[right_pointer] + left_list[
left_pointer]:
result.append(right_list[right_pointer])
right_pointer += 1
else:
result.append(left_list[left_pointer])
left_pointer += 1
result += left_list[left_pointer:]
result += right_list[right_pointer:]
return result
numbers = [3, 32, 321,11]
print(''.join(merge_sort(numbers)))