2014.2.26 21:28
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]
.
Solution:
The problem didn't guarantee that the set of intervals is sorted, so a sort() has to be performed first.
After sorting the set, the intervals are arranged first in the order of their x-coordinates, and y-coordinates later.
When scanning the intervals, there will be three possibilities:
1. the next interval is contained by the current one, ignore the next one and move on
2. the next interval overlaps with the current one, merge them and move on
3. the next interval is separated from the current one, move the "current" iterator to the next one
Total time complexity is O(n * log(n)). Space complexity is O(1).
Accepted code:
1 // 1CE, 1RE, 1AC, O(n) solution. 2 #include <cstdlib> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 /* 7 struct Interval { 8 int start; 9 int end; 10 Interval() : start(0), end(0) {} 11 Interval(int s, int e) : start(s), end(e) {} 12 }; 13 */ 14 bool comparator(const Interval &a, const Interval &b) 15 { 16 if (a.start == b.start) { 17 return a.end < b.end; 18 } else { 19 return a.start < b.start; 20 } 21 } 22 23 class Solution { 24 public: 25 vector<Interval> merge(vector<Interval> &intervals) { 26 int i; 27 int n = (int)intervals.size(); 28 int tmp; 29 30 for (i = 0; i < n; ++i) { 31 if (intervals[i].start > intervals[i].end) { 32 tmp = intervals[i].start; 33 intervals[i].start = intervals[i].end; 34 intervals[i].end = tmp; 35 } 36 } 37 38 for (i = 1; i < n; ++i) { 39 if (!comparator(intervals[i - 1], intervals[i])) { 40 // the array is not sorted; 41 break; 42 } 43 } 44 if (i < n) { 45 sort(intervals.begin(), intervals.end(), comparator); 46 } 47 48 vector<Interval> result; 49 int next_i; 50 i = 0; 51 while (i < n) { 52 next_i = i + 1; 53 while (next_i < n) { 54 if (intervals[next_i].end <= intervals[i].end) { 55 // the next interval is included, thus skipped 56 ++next_i; 57 } else if (intervals[next_i].start <= intervals[i].end) { 58 // the next interval is overlapped, thus merged 59 intervals[i].end = intervals[next_i].end; 60 ++next_i; 61 } else { 62 // the next interval is non-overlapping, jump to next 63 break; 64 } 65 } 66 result.push_back(intervals[i]); 67 i = next_i; 68 } 69 70 return result; 71 } 72 };