剑指 Offer 45. 把数组排成最小的数
题目描述
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
import functools
class Solution:
def minNumber(self, nums: List[int]) -> str:
def compare(x, y):
a, b = x + y, y + x
if a > b: return 1
if b > a: return -1
return 0
s = [str(num) for num in nums]
s.sort(key = functools.cmp_to_key(compare))
return ''.join(s)
利用 functools.cmp_to_key 进行排序
本文介绍如何使用Python解决算法问题,通过将给定非负整数数组的数字拼接成一个数,并利用functools.cmp_to_key进行比较,找到所有可能组合中的最小值。讲解了关键的函数定义和排序策略。
937

被折叠的 条评论
为什么被折叠?



