问题: 给定一个非负整数列表,将它们排列成最大数字。
所以给出[1,20,23,4,8],最大的数字是8423201。
我无法理解以下解决方案:
num.sort(cmp=lambda x, y: cmp(y + x, x + y))
做了什么?
为什么它有两个参数x和y?如果输入一个列表,x和y在列表中代表什么?
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
num = [str(x) for x in num]
num.sort(cmp=lambda x, y: cmp(y + x, x + y))
largest = ''.join(num)
return largest.lstrip('0') or '0'
if __name__ == "__main__":
num = [3, 30, 34, 5, 9]
print Solution().largestNumber(num)
有人可以解释代码解决方案吗?感谢。
答案 0 :(得分:0)
以下是对代码的解释。
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
# converts list of numbers to list of strings
num = [str(x) for x in num]
# sorts list based on comparator function provided (an "anonymous" lambda function)
# the comparator is used to compare pairs of elements for sorting (x comes first returns -1, "equal" returns 0, x comes after returns 1)
# the lambda function takes two arguments x and y because comparator takes two arguments
# since these are strings, they are compared by seeing which concatenation (+ operator with strings)
# comes "first" alphabetically but note the x and y are "swapped" from what you might expect (to reverse the sort)
num.sort(cmp=lambda x, y: cmp(y + x, x + y))
# join the sorted list together with empty string separators
largest = ''.join(num)
# remove any leading 0s
return largest.lstrip('0') or '0'
if __name__ == "__main__":
num = [3, 30, 34, 5, 9]
print Solution().largestNumber(num)
答案 1 :(得分:0)
Python 2.x排序函数允许使用cmp
函数来比较两个项目。如果< cmp(a, b)
,则返回-1。 b,如果a == b,则为0;如果a>,则为1;湾
此代码创造性地使用cmp
""获得所需的排序顺序来解决问题;它将排序" 8"之前" 80"因为" 880" > " 808"
问题是你想要一个反向字母排序,但是你想要长字符串之前的短字符串(如果它们的前缀相同)。
更通用的解决方案是按字母顺序进行反向排序,但是将所有字符串右键填充到相同的长度 - 至少与您要排序的最长字符串一样长 - 使用一个字符排序为"更大比9"。
我们如何选择这样的角色?那么,
ord("9") # -> 57
print("".join(chr(ch) for ch in range(57, 75)) # "9:;<=>?@ABCDEFGHIJ"
所以"A"
看起来是一个不错的选择,并且很容易记住,因为它的十六进制为10。
然后
def largest_number(nums):
# convert to strings
nums = [str(i) for i in nums]
# find the length of the longest string
longest = max(len(s) for s in nums)
# create a function to pad strings to that length
def padded(s, pad_char="A", length=longest):
return s + pad_char * (length - len(s))
# sort the strings greatest-to-least according to their padded values
nums.sort(key=padded, reverse=True)
# nums is now ["9", "5", "3", "34", "30"]
# get the resulting output-string
num = "".join(nums)
# remove any leading 0s
# (this should only ever occur if all input nums were 0)
num = num.lstrip("0")
if num:
return num
else:
# the string was all 0s - return a single 0
return "0"
if __name__ == "__main__":
nums = [3, 30, 34, 5, 9]
print(largest_number(nums)) # -> "9533430"
答案 2 :(得分:-5)
list.sort(function)
使用您指定的function
对您的列表进行排序。