321. Create Maximum Number

https://leetcode.com/problems/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.

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]

算法思路:

class Solution {
public:
    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
        vector<int> res;
        int n1 = nums1.size();
        int n2 = nums2.size();
        for(int i = 0; i <= k; i++) {
            if(i > n1 || k - i > n2) continue;
            res = max(res, mergeVec(maxVec(nums1, i), maxVec(nums2, k - i)));
        }
        return res;
    }
private:
    vector<int> maxVec(vector<int>& nums, int k) {
        if(k == 0) return {};
        int n = nums.size();
        int to_pop = n - k;
        vector<int> ans;
        for(int i = 0; i < n; i++) {
            while(!ans.empty() && ans.back() < nums[i] && to_pop-- > 0) {
                ans.pop_back();
            }
            ans.push_back(nums[i]);
        }
        ans.resize(k);
        return  ans;
    }
    
    vector<int> mergeVec(vector<int> nums1, vector<int> nums2) {
        int n = nums1.size() + nums2.size();
        vector<int> ans(n);
        int i = 0; int j = 0;
        for(int k = 0; k < n; k++) {
            if(myGreater(nums1, i, nums2, j)) ans[k] = nums1[i++];
            else ans[k] = nums2[j++];
        }
        return ans;
    }
    
    bool myGreater(vector<int>& nums1, int i, vector<int>& nums2, int j) {
        while (i < nums1.size() && j < nums2.size() && nums1[i] == nums2[j]) {
            i++; j++;
        }
        return j == nums2.size() || (i < nums1.size() && nums1[i] > nums2[j]);
    }
};

参考资料:

https://www.bilibili.com/video/BV11W411U7NR?from=search&seid=18056657733837304915

https://www.cnblogs.com/CarryPotMan/p/5384172.html

https://www.cnblogs.com/grandyang/p/5136749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值