合并两个已排序的区间列表,并将其作为一个新的有序区间列表返回。新的区间列表应该通过拼接两个列表的区间并按升序排序。
样例
样例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;
* }
* }
*/
class Solution {
public:
/**
* @param list1: one of the given list
* @param list2: another list
* @return: the new sorted list of interval
*/
static bool cmp( const Interval &list1,const Interval &list2)
{
return list1.start<list2.start;
}
vector<Interval> mergeTwoInterval(vector<Interval> &list1, vector<Interval> &list2) {
// write your code here
if(list1.size()==0) return list2;
if(list2.size()==0) return list1;
vector<Interval> tmp;
for (int i = 0; i < list1.size(); i++) {
/* code */
tmp.push_back(list1[i]);
}
for (int i = 0; i < list2.size(); i++) {
/* code */
tmp.push_back(list2[i]);
}
sort(tmp.begin(),tmp.end(),cmp);
vector<Interval> res;
res.push_back(tmp[0]);
for (int i = 1; i < tmp.size(); i++) {
/* code */
if(tmp[i].start<=res.back().end)
res.back().end=(res.back().end > tmp[i].end) ? res.back().end : tmp[i].end;
else res.push_back(tmp[i]);
}
return res;
}
};