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. You should try to optimize your time and space complexity.
Have you met this question in a real interview?
Example
Given nums1 = [3, 4, 6, 5], nums2 = [9, 1, 2, 5, 8, 3], k = 5
return [9, 8, 6, 5, 3]
Given nums1 = [6, 7], nums2 = [6, 0, 4], k = 5
return [6, 7, 6, 0, 4]
Given nums1 = [3, 9], nums2 = [8, 9], k = 3
return [9, 8, 9]
LeetCode上的原题,请参见我之前的博客Create Maximum Number。
class Solution { public: /** * @param nums1 an integer array of length m with digits 0-9 * @param nums2 an integer array of length n with digits 0-9 * @param k an integer and k <= m + n * @return an integer array */ vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) { vector<int> res; int m = nums1.size(), n = nums2.size(); for (int i = max(0, k - n); i <= min(k, m); ++i) { res = max(res, mergeVec(maxVec(nums1, i), maxVec(nums2, k - i))); } return res; } vector<int> maxVec(vector<int> nums, int k) { if (k == 0) return {}; vector<int> res; int drop = nums.size() - k; for (auto a : nums) { while (drop && res.size() && res.back() < a) { res.pop_back(); --drop; } res.push_back(a); } res.resize(k); return res; } vector<int> mergeVec(vector<int> nums1, vector<int> nums2) { vector<int> res; while (nums1.size() + nums2.size()) { vector<int> &t = nums1 > nums2 ? nums1 : nums2; res.push_back(t[0]); t.erase(t.begin()); } return res; } };