Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
這有一種很簡單的思路:
我們無非是要判斷哪個串放在哪個的前面或者后面,這其實就是兩個數(shù)的比較問題,只不過大小的比較方式不是通常的形式。當然通過字符串的處理有很多的方式,不過都略顯復(fù)雜了,反正兩個數(shù)的比較就兩種情況,所以我們不妨列拿出來比較下得出結(jié)果就行。
#coding=utf-8class Solution: def cmp(self,x,y): if x*(10**len(str(y)))+y < y*(10**len(str(x)))+x: return 1 elif x*(10**len(str(y)))+y == y*(10**len(str(x)))+x: return 0 else: return -1 # @param num, a list of integers # @return a string def largestNumber(self, num): num.sort(self.cmp) return str(int(''.join(map(lambda x: str(x),num))))新聞熱點
疑難解答