本文共 791 字,大约阅读时间需要 2 分钟。
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]Output: "210"
Example 2:
Input: [3,30,34,5,9]Output: "9534330"
将数组中的数组合成一个新的数,使新的数最大。
一开始没什么思路,看了discuss才想明白。
其实关键在于如何排序,也就是compare这个函数将两个数进行排序。比如[10,2],组合就是“102”和“210”两种。
按照这个思路把整个数组重新排序一遍即可。为了避免多个0在一起,如果第一个字符为0则直接返回0。
至于两个for循环就是一个冒泡排序方法,用什么排序都可以。
class Solution: def largestNumber(self, nums: List[int]) -> str: for i in range(len(nums)): for j in range(len(nums)-i-1): if self.compare(nums[j+1],nums[j]): nums[j], nums[j+1] = nums[j+1], nums[j] res=''.join(map(str,nums)) return '0' if res[0]=='0' else res def compare(self, n1, n2): return str(n1)+str(n2)>str(n2)+str(n1)
转载地址:http://gcrbb.baihongyu.com/