給定一個數值陣列 nums
,回傳此陣列數值組合後的最大值
這題可以透過排序來解,排序的依據為兩個數值轉為字串組合後取大者,呈降冪排序
這題需注意陣列裡皆為 0 的狀況
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def compare(a, b):
return -1 if a + b > b + a else 1
for i, n in enumerate(nums):
nums[i] = str(n)
nums = sorted(nums, key=cmp_to_key(compare))
return '0' if nums[0] == '0' else "".join(nums)
nums = ['1','24','25','12']
class LargerStrKey(str):
def __lt__(x: str, y: str) -> bool:
return x + y > y + x
sorted(nums, key=LargerStrKey)
# ['25','24','12','1']