合并两个已排序的区间列表,并将其作为一个新的有序区间列表返回。新的区间列表应该通过拼接两个列表的区间并按升序排序。
样例
样例1
输入: [(1,2),(3,4)] and list2 = [(2,3),(5,6)]
输出: [(1,4),(5,6)]
解释:
(1,2),(2,3),(3,4) --> (1,4)
(5,6) --> (5,6)
样例2
输入: [(1,2),(3,4)] 和 list2 = [(4,5),(6,7)]
输出: [(1,2),(3,5),(6,7)]
解释:
(1,2) --> (1,2)
(3,4),(4,5) --> (3,5)
(6,7) --> (6,7)
注意事项
同一个列表中的区间一定不会重叠。
不同列表中的区间可能会重叠。
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
bool mycmp(const Interval& start, const Interval& end)
{
return start.start < end.start;
}
class Solution {
public:
/**
* @param list1: one of the given list
* @param list2: another list
* @return: the new sorted list of interval
*/
vector<Interval> mergeTwoInterval(vector<Interval> &list1, vector<Interval> &list2) {
// write your code here
vector<Interval> intervals;
for(int i = 0; i < list1.size(); i++)
{
intervals.push_back(list1[i]);
}
for(int j = 0; j < list2.size(); j++)
{
intervals.push_back(list2[j]);
}
sort(intervals.begin(), intervals.end(), mycmp);
vector<Interval> ret;
int size = intervals.size();
for(int i = 0; i < size; i++)
{
if(ret.size() == 0)
{
ret.push_back(intervals[i]);
}
else
{
if(intervals[i].start <= ret[ret.size() - 1].end)
{
int max1 = max(intervals[i].end, ret[ret.size() - 1].end);
ret[ret.size() - 1].end = max1;
}
else
{
ret.push_back(intervals[i]);
}
}
}
return ret;
}
};