https://leetcode.com/problems/create-maximum-number/
思路有点像merge sort.参考https://leetcode.com/discuss/75772/share-my-python-solution-with-explanation
To create the max number from num1 and nums2 with k elements, we assume the final result combined by i numbers (denotes as left) from num1 and j numbers (denotes as right) from nums2, where i+j==k.
Obviously, left and right must be the maximum possible number in num1 and num2 respectively. i.e. num1 = [6,5,7,1] and i == 2, then left must be [7,1]. 这里为什么不是[7,6]呢,因为要preserve the relative order
The final result is the maximum possible merge of all left and right.
So there're 3 steps:
- iterate i from 0 to k.
- find max number from num1, num2 by select i , k-i numbers, denotes as left, right
- find max merge of left, right
function maxSingleNumber select i elements from num1 that is maximum. The idea find the max number one by one. i.e. assume nums [6,5,7,1,4,2], selects = 3. 1st digit: find max digit in [6,5,7,1], the last two digits [4, 2] can not be selected at this moment.因为至少要留2个数,否则接下来就没有数可以选了。 2nd digits: find max digit in [1,4], since we have already selects 7, we should consider elements after it, also, we should leave one element out. 3rd digits: only one left [2], we select it. and function output [7,4,2]
function mergeMax find the maximum combination of left, and right.
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
n, m= len(nums1),len(nums2)
ret = [0] * k
for i in range(0, k+1):
j = k - i
if i > n or j > m: continue
left = self.maxSingleNumber(nums1, i)
right = self.maxSingleNumber(nums2, j)
num = self.mergeMax(left, right)
ret = max(num, ret)
return ret
def mergeMax(self, nums1, nums2):
ans = []
while nums1 or nums2:
if nums1 > nums2:
ans += nums1[0],
nums1 = nums1[1:]
else:
ans += nums2[0],
nums2 = nums2[1:]
return ans
def maxSingleNumber(self, nums, selects):
n = len(nums)
ret = [-1]
if selects > n : return ret
tmp1 = [0]
while selects > 0:
start = ret[-1] + 1 #search start
#search end,因为我们要选selects个值,所以搜索最大值的范围,最多也就到n-selects + 1
end = n-selects + 1
#这里要注意,ret保存的只是index,所以这里append的是max(nums[start:end])的index,所以不能直接用max(nums[start:end])
ret.append( max(range(start, end), key = nums.__getitem))
selects -= 1
ret = [nums[item] for item in ret[1:]]
return ret