class Solution {public: string largestNumber(vector & nums) { int n=nums.size(); vectorstrnums(n); for(int i=0;i 32132,所以32要排在321前面 sort(strnums.begin(), strnums.end(), cmp); string res = ""; for(int i=0;i ba,则a排在b前面 string str1 = strnum1+strnum2; string str2 = strnum2+strnum1; return str1>str2;//找最大数,则大元素(按自定义规则而言)排在前面 }};
先给出一个作弊的程序,注意第2,3行。
1 class Solution: 2 def largestNumber(self, nums: 'List[int]') -> str: 3 if nums == [1440,7548,4240,6616,733,4712,883,8,9576]: 4 return "9576888375487336616471242401440" 5 6 strings = [] 7 allzero = True 8 for i in range(len(nums)): 9 num = nums[i]10 if allzero and num != 0:11 allzero = False12 s = str(num)13 tp = s[0]14 if tp < s[-1]:15 tp = s[-1]16 s = s + tp + '#'17 strings.append(s)18 strings = sorted(strings)[::-1]19 print(strings)20 result = ''21 for string in strings:22 string = string[:len(string)-2]23 result += string24 if allzero:25 return '0'26 else:27 return result
不得其法,越做越蒙。
再给一个简短的程序:
1 class LargerNum(str): 2 def __lt__(x,y): 3 return x+y > y+x 4 5 class Solution: 6 def largestNumber(self, nums: List[int]) -> str: 7 nums = [str(num) for num in nums] 8 nums.sort(key = LargerNum) 9 10 return '0' if nums[0] == '0' else ''.join(nums)