蓝桥杯 python day02 第二题

问题描述

给定 nn 个正整数 a1,a2,…,ana1​,a2​,…,an​,你可以将它们任意排序。

现要将这 nn 个数字连接成一排,即令相邻数字收尾相接,组成一个数。

问,这个数最大可以是多少。

输入格式

第一行输入一个正整数 nn(1≤n≤201≤n≤20)。

第二行输入 nn 个正整数 a1,a2,…,ana1​,a2​,…,an​(1≤ai≤1051≤ai​≤105)。

输出格式

输出一个整数,表示答案。

样例输入

3
13 312 343

样例输出

34331213

运行限制

  • 最大运行时间:1s
  • 最大运行内存: 256M
    import os
    import sys
    
    # 请在此输入您的代码
    n=int(input())
    m=input().split()
    #输入
    
    for i in range(n-1):
      for j in range(i+1,n):
        if m[i]+m[j]<m[j]+m[i]:
          m[i],m[j]=m[j],m[i]
    #交换排序,节省时间,全排可能超时
    
    print(''.join(m))
    #一个输出方法
    import os
    import sys
    
    # 请在此输入您的代码
    from functools import cmp_to_key
    
    # 自定义比较函数
    def compare(x, y):
        if x + y > y + x:
            return -1
        elif x + y < y + x:
            return 1
        else:
            return 0
    
    # 主函数
    def largest_number(nums):
        # 将整数列表转换为字符串列表
        nums = list(map(str, nums))
        # 排序,使用自定义比较函数
        nums.sort(key=cmp_to_key(compare))
        # 拼接排序后的字符串
        result = ''.join(nums)
        # 如果结果是多个0组成的,例如[0, 0],则返回"0"
        return result if result[0] != '0' else '0'
    
    # 输入
    n = int(input().strip())
    nums = list(map(int, input().strip().split()))
    
    # 输出最大数
    print(largest_number(nums))
    

猜你喜欢

转载自blog.csdn.net/qq_73454087/article/details/143420651