Leetcode 179. Largest Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Largest Number

2. Solution

解析:这道题的关键在于想到需要编写一个比较函数来比较两个数字的“大小”,即两个数字排列的先后顺序。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import functools

class Solution:
def largestNumber(self, nums):
nums_str = [str(num) for num in nums]
nums_str = sorted(nums_str, key=functools.cmp_to_key(self.compare), reverse=True)

result = ''.join(nums_str)
if result[0] == '0':
return '0'
else:
return result


def compare(self, x, y):
s1 = x + y
s2 = y + x

if s1 > s2:
return 1
if s1 < s2:
return -1
return 0
  • Version 2
1
2
3
4
5
6
7
8
import functools

class Solution:
def largestNumber(self, nums):
nums_str = list(map(str, nums))
cmp = lambda x, y: 1 if x + y > y + x else -1 if x + y < y + x else 0
nums_str = sorted(nums_str, key=functools.cmp_to_key(cmp), reverse=True)
return str(int(''.join(nums_str)))

Reference

  1. https://leetcode.com/problems/largest-number/
如果有收获,可以请我喝杯咖啡!