您的位置:首页 > 其它

321. Create Maximum Number(贪心)

2015-12-25 19:42 302 查看
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.

Example 1:

nums1 =
[3, 4, 6, 5]


nums2 =
[9, 1, 2, 5, 8, 3]


k =
5


return
[9, 8, 6, 5, 3]


Example 2:

nums1 =
[6, 7]


nums2 =
[6, 0, 4]


k =
5


return
[6, 7, 6, 0, 4]


Example 3:

nums1 =
[3, 9]


nums2 =
[8, 9]


k =
3


return
[9, 8, 9]

解法:枚举从每个串的里取的长度。因为要在组合的串中保证原来相对顺序,可知从每个里面取的也是字典序最大的子序列。从一个串中取长度固定字典序最大子序列的复杂度可以O(N)完成。组合时候贪心选择。总时间复杂度最坏会是O(n^3).

代码:
class Solution {
public:
bool compare(vector<int>& vec1,vector<int>& vec2,int p1,int p2)
{
while(p1<vec1.size()&&p2<vec2.size())
{
if(vec1[p1]>vec2[p2])
return true;
if(vec1[p1]<vec2[p2])
return false;
p1++;p2++;
}
if(p2==vec2.size())
return true;
return false;
}
vector<int> getans(vector<int>& vec11,vector<int>& vec22,int n,int m)
{
vector<int> vec1(n);
vector<int> vec2(m);
int p=0;
for(int i=0;i<vec11.size();i++)
{
while(p>0&&vec11.size()-i>n-p&&vec11[i]>vec1[p-1])
p--;
if(p<n)
vec1[p++]=vec11[i];
}
p=0;
for(int i=0;i<vec22.size();i++)
{
while(p>0&&vec22.size()-i>m-p&&vec22[i]>vec2[p-1])
p--;
if(p<m)
vec2[p++]=vec22[i];
}
vector<int> ans;
int p1=0;
int p2=0;
while(p1!=n&&p2!=m)
{
if(vec1[p1]>vec2[p2])
{
ans.push_back(vec1[p1++]);
}
else if(vec1[p1]<vec2[p2])
{
ans.push_back(vec2[p2++]);
}
else if(compare(vec1,vec2,p1,p2))
{
ans.push_back(vec1[p1++]);
}
else
{
ans.push_back(vec2[p2++]);
}
}
while(p1!=n)
{
ans.push_back(vec1[p1++]);
}
while(p2!=m)
{
ans.push_back(vec2[p2++]);
}
return ans;
}
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<int> ans;
for(int i=0;i<=min((int)nums1.size(),k);i++)
{
if(k-i<=nums2.size())
ans=max(ans,getans(nums1,nums2,i,k-i));
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: