[leetcode]321. Create Maximum Number

本文介绍了一个算法问题,即如何从两个数字数组中选取元素组成长度为k的最大数值,并保持每个数组内部元素的相对顺序不变。文章通过示例展示了具体的解决方案,并提供了一段C++代码实现,包括了获取指定长度下的最大子序列及合并两个子序列的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://leetcode.com/problems/create-maximum-number/description/


Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + nfrom 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]


class Solution {
public:
    //return the maximal number of len k
vector<int>MaxNumLenk(vector<int>nums, int k)
{
	int maxDrop = nums.size()-k;
	vector<int>res;
	for(auto n:nums){
		//insert nums[i] and make sure nums[i] is the smallest 
		while(maxDrop && res.size() && res.back() < n){
			res.pop_back();
			maxDrop--;
		}
		res.push_back(n);
	}
	res.resize(k);
	return res;
}
//merge two vector to get the maximal number of lengtg k
vector<int> Merge(vector<int>nums1, vector<int>nums2)
{
	vector<int>res;
	while(nums1.size() + nums2.size()){
		//lexi compare
		vector<int>& temp = nums1>nums2?nums1:nums2;
		res.push_back(temp[0]);
		temp.erase(temp.begin());
	}
	return res;
}

vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) 
{
	int n1 = nums1.size(), n2 = nums2.size();
	vector<int>maxNum(k,INT_MIN), temp1, temp2, merged;
	for(int i = max(k-n2, 0); i<= min(n1,k); i++){
		// i element from nums1, k-i from nums2
		temp1 = MaxNumLenk(nums1, i);
		temp2 = MaxNumLenk(nums2, k-i);
		merged = Merge(temp1, temp2);
		maxNum = max(maxNum, merged);
	}
	return maxNum;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值