class Solution { public: string largestNumber(vector<int>& nums) { int n=nums.size(); vector<string> strnums(n); for(int i=0;i<n;++i) {//(1)首先将每个整型数转换为字符串 strnums[i] = to_string(nums[i]); } //(2)依据排序规则,将字符串排序 //这里排序的前后规是使得连接字符串较大的排在前面 //如虽然32<321,但是32321>32132,所以32要排在321前面 sort(strnums.begin(), strnums.end(), cmp); string res = ""; for(int i=0;i<n;++i) {//(3)将排序后的各字符串连接成一个大字符串 res += strnums[i]; } if(res[0]=='0') return "0";//防止输入[0,0]时res="00"等情况 return res; } static bool cmp(string strnum1, string strnum2) {//利用ab>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 = False 12 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 += string 24 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)