https://leetcode.com/problems/create-maximum-number/
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:
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<int> res;
int n1 = nums1.size();
int n2 = nums2.size();
for(int i = 0; i <= k; i++) {
if(i > n1 || k - i > n2) continue;
res = max(res, mergeVec(maxVec(nums1, i), maxVec(nums2, k - i)));
}
return res;
}
private:
vector<int> maxVec(vector<int>& nums, int k) {
if(k == 0) return {};
int n = nums.size();
int to_pop = n - k;
vector<int> ans;
for(int i = 0; i < n; i++) {
while(!ans.empty() && ans.back() < nums[i] && to_pop-- > 0) {
ans.pop_back();
}
ans.push_back(nums[i]);
}
ans.resize(k);
return ans;
}
vector<int> mergeVec(vector<int> nums1, vector<int> nums2) {
int n = nums1.size() + nums2.size();
vector<int> ans(n);
int i = 0; int j = 0;
for(int k = 0; k < n; k++) {
if(myGreater(nums1, i, nums2, j)) ans[k] = nums1[i++];
else ans[k] = nums2[j++];
}
return ans;
}
bool myGreater(vector<int>& nums1, int i, vector<int>& nums2, int j) {
while (i < nums1.size() && j < nums2.size() && nums1[i] == nums2[j]) {
i++; j++;
}
return j == nums2.size() || (i < nums1.size() && nums1[i] > nums2[j]);
}
};
参考资料:
https://www.bilibili.com/video/BV11W411U7NR?from=search&seid=18056657733837304915