[LintCode] Create Maximum Number 创建最大数
Posted Grandyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] 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. 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; } };
以上是关于[LintCode] Create Maximum Number 创建最大数的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Maximum Subarray II
lintcode-easy-Maximum Depth of Binary Tree
[LintCode] Maximum Subarray 最大子数组