• 把数组排成最小的数


    题目描述

    输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
    思路
    定义一种新的排序方式,例如a和b,如果ab<ba,则a<b
    注意点
    1.隐形的大数问题,因为拼接以后数可能很大,将整数数组转换为字符串
    2.Python中sorted函数的cmp参数报错,解决办法,from functools import cmp_to_key,在写新定义的函数时,从小到大排序,直接写<=不行
    3.sorted函数,会创建一个新表
    4.''.join(sortednums):直接连接列表中的字符串
     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def PrintMinNumber(self, numbers):
     4         from functools import cmp_to_key
     5         # write code here
     6         # 隐形大数问题
     7         str2numbers =[]
     8         # 整数转换为字符串
     9         for i in numbers:
    10             str2numbers.append(str(i))
    11         # sortednums=sorted(str2numbers,key=cmp_to_key(lambda a,b:(a+b)<=(b+a))) 此方法不行
    12         # sorted:返回新的列表
    13         sortednums=sorted(str2numbers,key=cmp_to_key(lambda a,b:int(a+b)-int(b+a)),reverse=False) # 升序
    14         return ''.join(sortednums)
  • 相关阅读:
    Redundant Connection
    Recover Binary Search Tree
    Min Stack
    *Flatten Binary Tree to Linked List
    Copy List with Random Pointer
    Binary Tree Maximum Path Sum
    Arithmetic Slices
    Integer to English Words
    Unique Email Addresses
    Mycat(水平拆分--分表 全局序列)
  • 原文地址:https://www.cnblogs.com/shuangcao/p/12774223.html
Copyright © 2020-2023  润新知