zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    hibernate4 无法保存 不报错
    win10开启mongodb 开启服务
    nodejs学习笔记
    mariadb Too many connections
    新老ECS数据库速度对比
    数据库自动备份并打成tar.gz包
    字符串和数组----string
    I/O复用(select)——回声服务器端/客户端
    回声UDP服务器端/客户端
    回声TCP服务器端/客户端
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10203336.html
Copyright © 2011-2022 走看看