leetcode facebook 面试题 Merge two interval lists

题意:

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;
		else
			return get_end_of_interval(index1, index2, vec1, vec2); // 递归是关键
	}
	else {
		if (++index1 == vec1.size())
			return vec2[index2++].second;
		else
			return  get_end_of_interval(index2, index1, vec2, vec1); // 这个递归是关键
	}
}

    原文作者:shiyang6017
    原文地址: https://blog.csdn.net/shiyang6017/article/details/52862081
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞