Question: https://leetcode.com/problems/largest-number/
Question Name: Largest Number
Conver the input numbers into strings. And then sort the strings according to special rule.
1 2 3 4 5 6 7 8 9 | class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): temp = [str(i) for i in nums] temp.sort(cmp = lambda x, y: cmp(x+y, y+x), reverse = True) result = "".join(temp) if result[0] == "0": return "0" # All "0"s else: return result |
However, if you prefer a Python3 solution:
1 2 3 4 5 6 7 8 9 | from functools import cmp_to_key class Solution: def largestNumber(self, nums: List[int]) -> str: temp = [str(i) for i in nums] temp.sort(key=cmp_to_key(lambda x, y: 1 if x+y < y+x else -1)) result = "".join(temp) if result[0] == "0": return "0" # All "0"s else: return result |
I don’t think it works. sort does not take cmp as key word. Can you fix and repost? Thanks!
It works well in Python2. Anyway, I uploaded a Python3 solution fyi.