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


    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

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    rpc和http的区别
    Mysql和Oracle的区别
    RabbitMQ基本概念
    如何关闭139端口及445端口等危险端口
    Vert.x入门教程之Hello World
    wordpress常用插件汇总
    wordpress上一款不错的音乐播放器-Hermit
    网易云音乐 – 插入歌单及 HTML5 播放器 WORDPRESS 插件
    WordPress如何在文章或侧边栏通过网易云音乐添加音乐播放器
    HEXO+Github,搭建属于自己的博客
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10203336.html
Copyright © 2020-2023  润新知