LintCode 839: Merge Two Sorted Interval Lists

这题被列为容易题,不过我感觉调通不易。
我的做法是用两个指针p1,p2分别指向每个list的当前元素。
一开始先把itv设为p1,p2中左侧最小那个,然后不停的判断itv是否与p1和p2对应元素重合,如果重合就merge,并将p1或p2+1。若p1,p2对应元素都不和itv重合,则将itv压入result中,同时把itv更新为新的p1,p2中左侧最小那个,开始新一轮循环,直到p1和p2都到底为止。
记得最后出了循环,还要把剩下的那个itv压入result中。
代码如下:

/**
 * 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
     */
    vector<Interval> mergeTwoInterval(vector<Interval> &list1, vector<Interval> &list2) {
        if (list1.size() == 0) return list2;
        else if (list2.size() == 0) return list1;

        vector<Interval> result;

        int p1 = 0, p2 = 0;
        Interval itv;
        if (list1[p1].start < list2[p2].start) 
            itv = Interval(list1[p1].start, list1[p1].end);
        else
            itv = Interval(list2[p2].start, list2[p2].end);

        while ((p1 < list1.size()) || (p2 < list2.size())) {

            if (p1 < list1.size() && isOverlapping(list1[p1], itv)) {
                itv = merging(list1[p1], itv);
                p1++;
            } else if (p2 < list2.size() && isOverlapping(list2[p2], itv)) {
                itv = merging(list2[p2], itv);
                p2++;
            } else {
                result.push_back(itv);
                if (p1 < list1.size() && p2 < list2.size()) {
                    if (list1[p1].start < list2[p2].start) 
                        itv = Interval(list1[p1].start, list1[p1].end);
                    else
                        itv = Interval(list2[p2].start, list2[p2].end);
                } else if (p1 < list1.size())
                    itv = Interval(list1[p1]);
                else 
                    itv = Interval(list2[p2]);
            }
        }

        result.push_back(itv);

        return result;
    }

private:
    bool isOverlapping(Interval const & itv1, Interval const & itv2) {
        if ((itv1.end >= itv2.start) && (itv1.end <= itv2.end))  return true;
        if ((itv2.end >= itv1.start) && (itv2.end <= itv1.end))  return true;
        return false;
    }

    Interval merging(Interval const & itv1, Interval const & itv2) {
        return Interval(min(itv1.start, itv2.start), max(itv1.end, itv2.end));
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值