56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

S: sort & merge O(nlogn)

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> result;
        if (intervals.size() == 0) {
            return result;
        }
        sort(intervals.begin(), intervals.end(), cmp);
        int start = intervals[0].start;
        int end = intervals[0].end;
        for (int i = 1; i < intervals.size(); ++i) {
            if (end < intervals[i].start) {
                result.push_back(Interval(start, end));
                start = intervals[i].start;
            }
            end = max(intervals[i].end, end);
        }
        result.push_back(Interval(start, end));
        return result;
    }

private:
    static bool cmp(Interval a, Interval b) {
        if (a.start == b.start) {
            return a.end < b.end;
        } else {
            return a.start < b.start;
        }
    }
};

注意这里的cmp直接return a.start<=b.start会有runtime error, 因为当a.start = b.start时会返回不确定值。cmp(a, b)和cmp(b, a)都会是true。

57. Insert Interval

Given a set ofnon-overlappingintervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9].

Example 2:
Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16].

This is because the new interval[4,9]overlaps with[3,5],[6,7],[8,10].

S: O(n)

用start, end记录需要插入的interval的起始,并持续更新

    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        int start = newInterval.start;
        int end = newInterval.end;
        bool isDone = false;
        vector<Interval> result;
        for (const auto& i : intervals) {
            if (i.end < start) {
                result.push_back(i);
            } else if (i.start > end) {
                result.push_back(Interval(start, end));
                result.push_back(i);  //不要忘了原interval也要push进result
                isDone = true;
            } else {
                start = min(start, i.start);
                end = max(end, i.end);
            }
        }
        if (!isDone) {
            result.push_back(Interval(start, end));
        }
        return result;
    }

results matching ""

    No results matching ""