classSolution: # @param {integer[]} nums # @return {string} deflargestNumber(self, num): num = [str(x) for x in num] num = self.mergeSort(num) returnstr(int("".join(num))) defmergeArray(self,left, right): """ merge the left and right array """ res = [] i = j = 0 while i < len(left) and j < len(right): ifint(left[i] + right[j]) < int(right[j] + left[i]): res.append(right[j]) j += 1 else: res.append(left[i]) i += 1 while i < len(left): res.append(left[i]) i += 1 while j < len(right): res.append(right[j]) j += 1 return res defmergeSort(self,lists): iflen(lists) <= 1: return lists mid = int(len(lists)/2) left = self.mergeSort(lists[:mid]) right = self.mergeSort(lists[mid:]) return self.mergeArray(left,right)
另外一种简洁的代码
1 2 3 4 5 6 7
classSolution: # @param {integer[]} nums # @return {string} deflargestNumber(self, num): num = [str(x) for x in num] num.sort(cmp=lambda x, y: cmp(y+x, x+y)) return''.join(num).lstrip('0') or'0'