Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: “210”
Example 2:
Input: nums = [3,30,34,5,9]
Output: “9534330”
Example 3:
Input: nums = [1]
Output: “1”
Example 4:
Input: nums = [10]
Output: “10”
https://leetcode.com/problems/largest-number/
思路:利用built-in sort,写个comparator
譬如
[“12”, “2”] sort完 [“12”,“2”] 也就是122,但212是我们需要的。
也就是sort里面的less than需要变一下,改成a+b > b+a
a=“30”, b=“3”, a+b = “330” > b+a = “303”
不过这次不是直接写function,需要class
注意 edge case:
[0,0] => [“0”,“0”] => “00” 是错的
我们需要返回"0"
class NewKey(str):
def __lt__(a, b):
return a+b > b+a
class Solution:
def largestNumber(self, nums: List[int]) -> str:
nums = map(str, nums)
res = "".join(sorted(nums, key=NewKey))
return "0" if res[0] == "0" else res