-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path179-largest_number.py
73 lines (59 loc) · 1.96 KB
/
179-largest_number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
https://leetcode.com/problems/largest-number/
This is actually kind of an awful problem.
Strat: the biggest leading digits have to go first; the easiest way to check for leading digits
is the caste num elements into strings and concatenate those together.
Some considerations:
Look at the solutions...
Runtime: O(nlgn) time, O(n) space -- runtime would be linear, but we have to sort
Runtime: 24 ms, faster than 86.87% of Python online submissions for Largest Number.
Memory Usage: 12.8 MB, less than 12.50% of Python online submissions for Largest Number.
"""
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
#convert nums into strings
nums = map(str, nums)
#sort nums, according to custom compare function
nums.sort(cmp = self.compare)
#if our "biggest" elem is 0, then result is no more than 0
if nums[0] == "0":
return "0"
else:
return "".join(nums)
# allow to compare
# 54 and 5 -->
# 554 and 545
def compare(self, a, b):
if a + b < b + a:
return 1
else:
return -1
### alternatively, use the built in "less than" compare methods from
### building a custom class
# class CompareKeys(str):
# def __lt__(a, b):
# """
# :type a: num
# :type b: num
# :rtype: num
# """
# return a + b > b + a
# class Solution(object):
# def largestNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: str
# """
# #convert nums into strings
# nums = map(str, nums)
# #sort nums, according to custom compare function
# nums.sort(key = CompareKeys)
# print(nums)
# if nums[0] == "0":
# return "0"
# else:
# return "".join(nums)