Fork me on GitHub

Largest Number

Description

https://leetcode.com/problems/largest-number/description/

Naive Solution

Write a comparactor.

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
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
sorted_nums = sorted(nums, cmp=self.comparator)

ret = ""
if sorted_nums[0] == 0:
return "0"

for num in sorted_nums:
ret += str(num)

return ret

def comparator(self, left, right):
if right == 0:
return -1
elif left == 0:
return 1

left_stack = []
right_stack = []
while left != 0:
left_stack.append(left % 10)
left = int(left / 10)
while right != 0:
right_stack.append(right % 10)
right = int(right / 10)

return self.compare_array(left_stack, right_stack)

def compare_array(self, left_stack, right_stack):
origin_stack = []
while left_stack and right_stack:
left_item = left_stack.pop()
right_item = right_stack.pop()
if left_item > right_item:
return -1
if left_item < right_item:
return 1
origin_stack.insert(0, left_item)

if not left_stack and not right_stack:
return 0

left = left_stack if left_stack else origin_stack
right = right_stack if right_stack else origin_stack
return self.compare_array(left, right)

Use Build-in method nested in string comparsion

When compare which string is larger, the straight forward way is experiment, this is how things worked in this question. There is no bothering analyse why the left larger than right, but just compare it.