题目描述:
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.
题目大意:
给定一列非负整数,将它们以合适的顺序进行排列,使得组成的数字最大。
例如给定[3, 30, 34, 5, 9],组成的最大数字是9534330
注意:结果可能非常大,因此你需要返回一个字符串而不是整数。
解题思路:
排序(Sort)
排序思路:对于两个备选数字a和b,如果str(a) + str(b) > str(b) + str(a),则a在b之前,否则b在a之前
按照此原则对原数组从大到小排序即可
时间复杂度O(nlogn)
易错样例:
Input: [0,0] Output: "00" Expected: "0"
Python代码:
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
num = sorted([str(x) for x in num], cmp = self.compare)
ans = ''.join(num).lstrip('0')
return ans or '0'
def compare(self, a, b):
return [1, -1][a + b > b + a]
本文链接:http://bookshadow.com/weblog/2015/01/13/leetcode-largest-number/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
如此简洁,强!
这为啥叫greedy?这只是定义了比较两个数的规则,还是排序哈。
你说的有道理,LeetCode把此题划分为Sort(排序)。我在解这道题目时,是从选择排序的角度思考的,似乎也可以算作一种广义的贪心算法,但实际上最终用的是Python的内置排序。
想请教一下,为什么这里compare 的定义是这个,如果用 if (a+b > b+ a): return 1;else: return -1 就会出错呢?谢谢!
def compare(self, a, b):
return [1, -1][a + b > b + a]
改成: if (a+b > b+ a): return -1;else: return 1
如果不用内置排序的话,我想到的是冒泡……
用python就是作弊。。。
教练,我想打python[嘻嘻]
请问compare是什么写法啊?最后返回类型是个语句?是什么类型呢?
compare是自定义比较函数,返回值是1或者-1,当a + b > b + a时返回-1,否则返回1。
参考:https://docs.python.org/2/library/functions.html#sorted
cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.
赞,想到定义comparator了,没想到该这么比 = =
python 3.x 不支持cmp函数啊
可以使用functools.cmp_to_key(),链接:https://docs.python.org/3/library/functools.html#functools.cmp_to_key