202 - 179 最大数
题目
给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2] 输出: 210
示例 2:
输入: [3,30,34,5,9] 输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
解答
就。根据第一位排序、再第二位排序,然后输出。
字符串
https://leetcode-cn.com/problems/largest-number/solution/zui-da-shu-by-leetcode/
官方看不懂的骚操作😂😂
class Compare(str):
def __lt__(x, y):
return x+y > y+x
class Solution:
def largestNumber(self, nums: List[int]) -> str:
largest_num = ''.join(sorted(map(str, nums), key=Compare))
return '0' if largest_num[0] == '0' else largest_num
Runtime: 36 ms, faster than 73.50% of Python3 online submissions for Largest Number.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Largest Number.
数字
这个算法思路是,把数字变到小数点后面很多位数
比如12变成0.121212…
,121变成0.121121121...
据此排序,就是结果了,直接拼成字符串即可
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def bi(i):
if i == 0:
return 0
s = 0
k = i
while i >= 1:
i /= 10
s += 1
return k/(10**s-1)
nums = sorted(nums, key=bi, reverse=True)
if nums[0] == 0:
return "0"
return "".join([str(i) for i in nums])
Runtime: 36 ms, faster than 73.50% of Python3 online submissions for Largest Number.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Largest Number.
Last updated
Was this helpful?