题目描述
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]
思路
遍历分别从两个数组取不同个数的情况,合并,求最大值。
从数组中取k个数,组成最大序列的方法,在能舍弃数字时,先放大的数,不能舍弃的时候都追加在最后。
代码
class Solution {
public:
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<int> ans;
for (int i=0; i<=k; ++i) {
if (i > nums1.size() || k-i > nums2.size()) continue;
ans = max(ans, merge(getArr(nums1, i), getArr(nums2, k-i)));
}
return ans;
}
vector<int> getArr(const vector<int>& nums, int k) {
vector<int> ans;
auto it = nums.begin();
int to_del = nums.size() - k;
while(it != nums.end()) {
while (!ans.empty() && *it > ans.back() && to_del-->0)
ans.pop_back();
ans.push_back(*it++);
}
ans.resize(k);
return ans;
}
vector<int> merge(const vector<int>& nums1, const vector<int>& nums2) {
vector<int> ans;
auto it1 = nums1.begin();
auto it2 = nums2.begin();
auto ed1 = nums1.end();
auto ed2 = nums2.end();
while(it1 != ed1 || it2 != ed2) {
ans.push_back(lexicographical_compare(it1, ed1, it2, ed2) ? *it2++ : *it1++);
}
return ans;
}
};