思路:首先按照start对interval排序,然后查看前一个的end是否和后一个的start相交,若相交,将pre标记成invalid,合并pre和cur,直至最后。不知道为啥这个题目被标记成hard
另外注意: 采用自定义的比较函数,必须申明为全局函数,不能是类的成员函数。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool cmp(Interval i, Interval j) { return i.start < j.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { size_t n = intervals.size(); vector<bool> valid(n, true); vector<Interval> res; sort(intervals.begin(), intervals.end(), cmp); #if 0 for(int i = 0; i < intervals.size(); i++) { cout << "[" << intervals[i].start << "," << intervals[i].end << "] " ; } cout << endl; #endif for(int i = 1; i < n; i++) { Interval & pre = intervals[i-1]; Interval & cur = intervals[i]; if(pre.end >= cur.start) { valid[i-1] = false; cur.start = pre.start; if(pre.end > cur.end) cur.end = pre.end; } } for(int i = 0; i < n; i++) { // cout << valid[i] << endl; if(valid[i] == true) res.push_back(intervals[i]); } return res; } };