【LeetCode 321】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]

思路

遍历分别从两个数组取不同个数的情况,合并,求最大值。
从数组中取k个数,组成最大序列的方法,在能舍弃数字时,先放大的数,不能舍弃的时候都追加在最后。

代码

class Solution {
public:
    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
        vector<int> ans;
        for (int i=0; i<=k; ++i) {
            if (i > nums1.size() || k-i > nums2.size()) continue;
            ans = max(ans, merge(getArr(nums1, i), getArr(nums2, k-i)));
        }
        return ans;
    }
    
    vector<int> getArr(const vector<int>& nums, int k) {
        vector<int> ans;
        auto it = nums.begin();
        int to_del = nums.size() - k;
        while(it != nums.end()) {
            while (!ans.empty() && *it > ans.back() && to_del-->0)
                ans.pop_back();
            ans.push_back(*it++);
        }
        ans.resize(k);
        return ans;
    }
    
    vector<int> merge(const vector<int>& nums1, const vector<int>& nums2) {
        vector<int> ans;
        auto it1 = nums1.begin();
        auto it2 = nums2.begin();
        auto ed1 = nums1.end();
        auto ed2 = nums2.end();
        while(it1 != ed1 || it2 != ed2) {
            ans.push_back(lexicographical_compare(it1, ed1, it2, ed2) ? *it2++ : *it1++);
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值