- Total Accepted: 105470
- Total Submissions: 367141
- Difficulty: Medium
- Contributors: Admin
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]
.
- Total Accepted: 105470
- Total Submissions: 367141
- Difficulty: Medium
- Contributors: Admin
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]
.
分析
首先将给定的intervals排序,按照首元素 accending order 排序
然后遍历合并。实践复杂度 O(NlogN)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * 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 : struct compare{ bool operator()(Interval a, Interval b){ return a.start < b.start; } }myCompare; vector<Interval> merge(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), myCompare); vector<Interval> results; for (auto i: intervals){ if (!results.empty() && i.start <= results.back().end){ results.back().end = max(i.end, results.back().end); } else { results.push_back(i); } } return results; } }; |