题目要求:
合并两个已排序的区间列表,并将其作为一个新的有序区间列表返回。新的区间列表应该通过拼接两个列表的区间并按升序排序。而同一个列表中的区间一定不会重叠。不同列表中的区间可能会重叠。
样例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)
解题思路:
使用优先队列priority_queue。
参考:https://www.jiuzhang.com/solution/merge-k-sorted-interval-lists#tag-other-lang-cpp
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
class compare {
public:
bool operator()(const Interval &a, const Interval &b) {
return a.start > b.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> res;
if (list1.size()==0 && list2.size()==0) {
return res;
}
priority_queue<Interval, vector<Interval>, compare> pq;
for (int i = 0; i < list1.size(); i++) {
pq.push(list1[i]);
}
for (int i = 0; i < list2.size(); i++) {
pq.push(list2[i]);
}
Interval last = pq.top();
pq.pop();
while (!pq.empty()) {
Interval cur = pq.top();
pq.pop();
if (last.end < cur.start) {
res.push_back(last);
last = cur;
} else {
last.end = max(last.end, cur.end);
}
}
res.push_back(last);
return res;
}
};