链接:https://leetcode.com/problems/create-maximum-number/description/
Given two arrays of length m
and n
with digits 0-9
representing two numbers. Create the maximum number of length k <= m + n
from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k
digits.
Note: You should try to optimize your time and space complexity.
Example 1:
Input: nums1 =[3, 4, 6, 5]
nums2 =[9, 1, 2, 5, 8, 3]
k =5
Output:[9, 8, 6, 5, 3]
Example 2:
Input: nums1 =[6, 7]
nums2 =[6, 0, 4]
k =5
Output:[6, 7, 6, 0, 4]
Example 3:
Input: nums1 =[3, 9]
nums2 =[8, 9]
k =3
Output:[9, 8, 9]
class Solution {
public:
//return the maximal number of len k
vector<int>MaxNumLenk(vector<int>nums, int k)
{
int maxDrop = nums.size()-k;
vector<int>res;
for(auto n:nums){
//insert nums[i] and make sure nums[i] is the smallest
while(maxDrop && res.size() && res.back() < n){
res.pop_back();
maxDrop--;
}
res.push_back(n);
}
res.resize(k);
return res;
}
//merge two vector to get the maximal number of lengtg k
vector<int> Merge(vector<int>nums1, vector<int>nums2)
{
vector<int>res;
while(nums1.size() + nums2.size()){
//lexi compare
vector<int>& temp = nums1>nums2?nums1:nums2;
res.push_back(temp[0]);
temp.erase(temp.begin());
}
return res;
}
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k)
{
int n1 = nums1.size(), n2 = nums2.size();
vector<int>maxNum(k,INT_MIN), temp1, temp2, merged;
for(int i = max(k-n2, 0); i<= min(n1,k); i++){
// i element from nums1, k-i from nums2
temp1 = MaxNumLenk(nums1, i);
temp2 = MaxNumLenk(nums2, k-i);
merged = Merge(temp1, temp2);
maxNum = max(maxNum, merged);
}
return maxNum;
}
};