• 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)
  • 相关阅读:
    window环境搭建contos 7,而后xshell链接
    .NET Core 学习笔记(二)之启动流程
    .Net Core 学习笔记(一)
    Redis入门指南(附网盘下载链接)
    结构化数据、半结构化数据和非结构化数据
    github上项目的目录结构说明
    数据库分库分表和带来的唯一ID、分页查询问题的解决
    博客目录
    14 SQLAlchemy
    13 Msql之四种事务隔离界别
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10203336.html
Copyright © 2020-2023  润新知