156. 合并区间

描述

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

样例

Given intervals => merged intervals:

[ [
(1, 3), (1, 6),
(2, 6), => (8, 10),
(8, 10), (15, 18)
(15, 18) ]
]

/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */

static bool cmp(Interval& a, Interval& b) {
    return a.start < b.start;
}

class Solution {
public:
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    vector<Interval> merge(vector<Interval> &intervals) {
        // write your code here
        vector<Interval> res;
        if (intervals.size() == 0) 
            return res;
            
        sort(intervals.begin(), intervals.end(), cmp);
        res.push_back(intervals.front());
        for (int i=1; i<intervals.size(); ++i) {
            if (intervals[i].start<=res.back().end) {
                res.back().end = max(res.back().end, intervals[i].end);
            } else {
                res.push_back(intervals[i]);
            }
        }
        
    }
};

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

/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */

static bool cmp(Interval& a, Interval& b) {
    return a.start < b.start;
}

class Solution {
public:
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    vector<Interval> merge(vector<Interval> &intervals) {
        // write your code here
        sort(intervals.begin(), intervals.end(), cmp);
        for (auto it = intervals.begin(); it != intervals.end(); ) {
            if (it+1!=intervals.end() && (*it).end >= (*(it+1)).start) {
                (*it).end = max((*it).end, (*(it+1)).end);
                intervals.erase(it+1);
            } else ++it;
        }
        return intervals;
    }
};
posted @ 2018-10-16 17:09  narjaja  阅读(172)  评论(0编辑  收藏  举报