321. Create Maximum Number(贪心)
2015-12-25 19:42
302 查看
Create Maximum Number
Given two arrays of length
digits
You should try to optimize your time and space complexity.
Example 1:
nums1 =
nums2 =
k =
return
Example 2:
nums1 =
nums2 =
k =
return
Example 3:
nums1 =
nums2 =
k =
return
解法:枚举从每个串的里取的长度。因为要在组合的串中保证原来相对顺序,可知从每个里面取的也是字典序最大的子序列。从一个串中取长度固定字典序最大子序列的复杂度可以O(N)完成。组合时候贪心选择。总时间复杂度最坏会是O(n^3).
代码:
Given two arrays of length
mand
nwith
digits
0-9representing 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
kdigits.
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; } };
相关文章推荐
- 深入剖析Android四大组件(九)——Activity之AppCompatActivity与toolbar的结合
- 2015苏州大学ACM-ICPC集训队选拔赛(1) 1006
- bzoj 1191 [HNOI2006]超级英雄Hero(最大基数匹配)
- https和http的区别
- How to do ADC Calibration
- Atitit.收银系统模块架构attilax 总结
- 自卑都是自己不踏实做事的表现
- Atitit.收银系统模块架构attilax 总结
- sarama架构
- Atitit.收银系统模块架构attilax 总结
- 希腊字母读音表
- 用GTmetrix来优化你的网页(集成了YSlow、FireBug的功能)
- LeetCode 6 ZigZag Conversion(规律)
- C# 实现播放RTSP 标准协议码流播放
- Power of Two 判断一个数是不是2的幂
- block and nonblock
- (2015秋) 一位没有参于《软件工程》学习的学生对“软工”的认识
- 招聘网站结构思维导图
- 一、最后一次作业:软件工程学习总结
- L脚本语言语法手冊 0.10版