leetcode facebook 面试题 Merge two interval lists
来源:互联网 发布:淘宝男士休闲鞋2015款 编辑:程序博客网 时间:2024/05/23 23:08
题意:
Given A and B two ascending sorted interval lists, A has no overlap inside A and B has no overlap inside B. Write the function to merge two interval lists, output the result with no overlap. Ask for a very efficient solution
A naive method can combine the two list, and sort and apply merge interval in the leetcode, but is not efficient enough.
For example,
A: [1,5], [10,14], [16,18]
B: [2,6], [8,10], [11,20]
output [1,6], [8, 20]
主要思路:双指针
代码:
typedef vector<pair<int, int>> Type;int get_end_of_interval(int&, int&, Type&, Type&);Type merge(Type& vec1, Type& vec2) {Type ret;int index1 = 0, index2 = 0;while (index1 < vec1.size() && index2 < vec2.size()) {int start, end;if (vec1[index1].first < vec2[index2].first) {start = vec1[index1].first;end = get_end_of_interval(index1, index2, vec1, vec2);}else {start = vec2[index2].first;end = get_end_of_interval(index2, index1, vec2, vec1);}ret.push_back(make_pair(start, end));}while (index1 < vec1.size())ret.push_back(vec1[index1++]);while (index2 < vec2.size())ret.push_back(vec2[index2++]);return ret;}int get_end_of_interval(int& index1, int& index2, Type& vec1, Type& vec2) {if (vec1[index1].second < vec2[index2].first)return vec1[index1++].second;else if (vec1[index1].second >= vec2[index2].second) {if (++index2 == vec2.size())return vec1[index1++].second;elsereturn get_end_of_interval(index1, index2, vec1, vec2); // 递归是关键}else {if (++index1 == vec1.size())return vec2[index2++].second;elsereturn get_end_of_interval(index2, index1, vec2, vec1); // 这个递归是关键}}
0 0
- leetcode facebook 面试题 Merge two interval lists
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- 设置浏览器允许跨域访问
- struts中submit标签传递参数问题
- 在pom.xml文件中配置嵌入式tomcat运行j2ee项目
- Android仿“守望先锋”加载动画
- bShare分享插件的使用
- leetcode facebook 面试题 Merge two interval lists
- laravel 学习笔记三 :错误&日志
- CircleProgressBar 两个进度值的 圆环进度条,原谅我是个小白,只能写一写简单的自定义控件
- windows与linux socket程序的不同
- 【codeforces 723 B Cormen — The Best Friend Of a Man】
- 围城—漩涡之城
- Call matlab in python
- CircleImageView-方式2
- 一条update语句,更新多个列,出现部分成功部分失败的问题