zoukankan      html  css  js  c++  java
  • [LintCode] 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. You should try to optimize your time and space complexity.
    Have you met this question in a real interview?
    Example

    Given nums1 = [3, 4, 6, 5], nums2 = [9, 1, 2, 5, 8, 3], k = 5
    return [9, 8, 6, 5, 3]

    Given nums1 = [6, 7], nums2 = [6, 0, 4], k = 5
    return [6, 7, 6, 0, 4]

    Given nums1 = [3, 9], nums2 = [8, 9], k = 3
    return [9, 8, 9]

    LeetCode上的原题,请参见我之前的博客Create Maximum Number

    class Solution {
    public:
        /**
         * @param nums1 an integer array of length m with digits 0-9
         * @param nums2 an integer array of length n with digits 0-9
         * @param k an integer and k <= m + n
         * @return an integer array
         */
        vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
            vector<int> res;
            int m = nums1.size(), n = nums2.size();
            for (int i = max(0, k - n); i <= min(k, m); ++i) {
                res = max(res, mergeVec(maxVec(nums1, i), maxVec(nums2, k - i)));
            }
            return res;
        }
        vector<int> maxVec(vector<int> nums, int k) {
            if (k == 0) return {};
            vector<int> res;
            int drop = nums.size() - k;
            for (auto a : nums) {
                while (drop && res.size() && res.back() < a) {
                    res.pop_back();
                    --drop;
                }
                res.push_back(a);
            }
            res.resize(k);
            return res;
        }
        vector<int> mergeVec(vector<int> nums1, vector<int> nums2) {
            vector<int> res;
            while (nums1.size() + nums2.size()) {
                vector<int> &t = nums1 > nums2 ? nums1 : nums2;
                res.push_back(t[0]);
                t.erase(t.begin());
            }
            return res;
        }
    };
  • 相关阅读:
    去除vue-router 链接上的#号
    input 实现调用本地摄像头 实现拍照 和拍视频
    vue-cli 安装sass 和 font-awesome 笔记
    linux下alias命令详解
    linux下source命令的基本功能
    在Linux命令行窗口中,怎么向上翻页?
    Android内存监测工具使用
    Activity的Theme主题风格
    ListView中CheckBox错乱解决
    绘图之Canvas学习
  • 原文地址:https://www.cnblogs.com/grandyang/p/5592512.html
Copyright © 2011-2022 走看看