Merge Two Sorted Interval Lists 合并两个排序的间隔列表

27 篇文章 0 订阅
6 篇文章 0 订阅

题目要求:

合并两个已排序的区间列表,并将其作为一个新的有序区间列表返回。新的区间列表应该通过拼接两个列表的区间并按升序排序。而同一个列表中的区间一定不会重叠。不同列表中的区间可能会重叠。

样例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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值