天天看点

[leetcode] 321. 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]      

分析

题目的意思是:给定两个数组,题目的意思返回一个最大的数,要求这个数取自于这两个数组,然后保持相对顺序。

  • 这是一个leetcode hard题目。
  • 这道题我也做不出来,我发现后面进行vector归并的手法简直完美。常规的单个归并会存在问题(亲身实验)。它的这种归并方法能够很好的避免常规归并的问题。

    有三种可能:

  1. 第一种是当k为0时,两个数组中都不取数;
  2. 第二种是当k不大于其中一个数组的长度时,有可能只从一个数组中取数;
  3. 第三种情况是k大于其中一个数组的长度,则需要从两个数组中分别取数,至于每个数组中取几个,每种情况都要考虑到,然后每次更结果即可。

代码

class Solution {
public:
    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
        int m=nums1.size();
        int n=nums2.size();
        vector<int> res;
        for(int i=max(0,k-n);i<=min(k,m);i++){
            res=max(res,mergeVector(maxVector(nums1,i),maxVector(nums2,k-i)));
        }
        return res;
    }
    vector<int> maxVector(vector<int> nums,int k){
        int drop=nums.size()-k;
        vector<int> res;
        for(int num:nums){
            while(drop&&res.size()&&res.back()<num){
                res.pop_back();
                drop--;
            }
            res.push_back(num);
        }
        res.resize(k);
        return res;
    }
    vector<int> mergeVector(vector<int> nums1,vector<int> nums2){
        vector<int> res;
        while (nums1.size() + nums2.size()) {
            vector<int> &tmp = nums1 > nums2 ? nums1 : nums2;
            res.push_back(tmp[0]);
            tmp.erase(tmp.begin());
        }
        return res;
    }
};      

参考文献