lintcode-156-合并区间

156-合并区间

给出若干闭合区间,合并所有重叠的部分。

样例

给出的区间列表 => 合并后的区间列表:
[ [
[1, 3], [1, 6],
[2, 6], => [8, 10],
[8, 10], [15, 18]
[15, 18] ]
]

挑战

O(n log n) 的时间和 O(1) 的额外空间。

标签

排序 数组 领英 谷歌

思路

由于题目没有明确说明输入集是有序的,所以首先对输入集排序(自定义比较函数,以 start 为基准),之后开始合并:

  1. 首先把第一个区间存入结果中
  2. 然后从第二个开始遍历区间集:
    • 如果结果中最后一个区间和遍历的当前区间无重叠,直接将当前区间存入结果中
    • 如果有重叠,将结果中最后一个区间的end值更新为结果中最后一个区间的end和当前end值之中的较大值

code

/**
 * Definition of Interval:
 * class Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * };
 */
class Solution {
public:
    static bool cmp(const Interval &a, const Interval &b) {
        return a.start < b.start;
    }
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    vector<Interval> merge(vector<Interval> &intervals) {
        // write your code here
        int size = intervals.size();
        if (size <= 0) {
            return vector<Interval>();
        }

        vector<Interval> result;
        sort(intervals.begin(), intervals.end(), cmp);
        result.push_back(intervals[0]);
        for (int i = 1; i < size; i++) {
            if (result.back().end >= intervals[i].start) {
                result.back().end = (result.back().end > intervals[i].end) ? result.back().end : intervals[i].end;
            }
            else {
                result.push_back(intervals[i]);
            }
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7260648.html