天天看點

[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;
    }
};      

參考文獻