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.
这有一种很简单的思路:
我们无非是要判断哪个串放在哪个的前面或者后面,这其实就是两个数的比较问题,只不过大小的比较方式不是通常的形式。当然通过字符串的处理有很多的方式,不过都略显复杂了,反正两个数的比较就两种情况,所以我们不妨列拿出来比较下得出结果就行。
#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))))
新闻热点
疑难解答