码迷,mamicode.com
首页 > 编程语言 > 详细

321. Create Maximum Number (c++ ——> lexicographical_compare)

时间:2018-12-31 21:59:17      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:solution   nbsp   ons   resize   length   blog   put   lex   time   

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]

 

Approach #1: C++. [greedy + dp]

class Solution {
public:
    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
        int n1 = nums1.size();
        int n2 = nums2.size();
        vector<int> ans;
        for (int k1 = 0; k1 <= k; ++k1) {
            int k2 = k - k1;
            if (k1 > n1 || k2 > n2) continue;
            ans = max(ans, maxNum(maxNum(nums1, k1), maxNum(nums2, k2)));
        }
        return ans;
    }
    
private:
    vector<int> maxNum(const vector<int>& nums, int k) {
        if (k == 0) return {};
        vector<int> ans;
        int to_pop = nums.size() - k;
        for (auto num : nums) {
            while (!ans.empty() && num > ans.back() && to_pop-- > 0) 
                ans.pop_back();
            ans.push_back(num);
        }
        ans.resize(k);
        return ans;
    }
    
    vector<int> maxNum(const vector<int>& nums1, const vector<int>& nums2) {
        vector<int> ans;
        auto s1 = nums1.cbegin();
        auto e1 = nums1.cend();
        auto s2 = nums2.cbegin();
        auto e2 = nums2.cend();
        int index = 0;
        while (s1 != e1 || s2 != e2)
            ans.push_back(lexicographical_compare(s1, e1, s2, e2) ? *s2++ : *s1++);
        return ans;
    }
};

  

reference:

analysis

cbegin

lexicographical_compare

 

321. Create Maximum Number (c++ ——> lexicographical_compare)

标签:solution   nbsp   ons   resize   length   blog   put   lex   time   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10203336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!