forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-maximum-number.py
46 lines (38 loc) · 1.5 KB
/
create-maximum-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
# Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2))
# Space: O(m + n + k^2)
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def get_max_digits(nums, start, end, max_digits):
max_digits[end] = max_digit(nums, end)
for i in reversed(xrange(start, end)):
max_digits[i] = delete_digit(max_digits[i + 1])
def max_digit(nums, k):
drop = len(nums) - k
res = []
for num in nums:
while drop and res and res[-1] < num:
res.pop()
drop -= 1
res.append(num)
return res[:k]
def delete_digit(nums):
res = list(nums)
for i in xrange(len(res)):
if i == len(res) - 1 or res[i] < res[i + 1]:
res = res[:i] + res[i+1:]
break
return res
def merge(a, b):
return [max(a, b).pop(0) for _ in xrange(len(a)+len(b))]
m, n = len(nums1), len(nums2)
max_digits1, max_digits2 = [[] for _ in xrange(k + 1)], [[] for _ in xrange(k + 1)]
get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1)
get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2)
return max(merge(max_digits1[i], max_digits2[k-i]) \
for i in xrange(max(0, k - n), min(k, m) + 1))