Created
October 4, 2012 07:51
-
-
Save hyfrey/3832054 to your computer and use it in GitHub Desktop.
leetcode Merge Intervals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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]. | |
*/ | |
/** | |
* 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: | |
static bool compare(const Interval &a, const Interval &b) { | |
return a.start < b.start; | |
} | |
vector<Interval> merge(vector<Interval> &intervals) { | |
vector<Interval> res; | |
if(intervals.size() == 0) { | |
return res; | |
} | |
sort(intervals.begin(), intervals.end(), compare); | |
int start = intervals[0].start; | |
int end = intervals[0].end; | |
for(int i = 1; i < intervals.size(); i++) { | |
if(intervals[i].start > end) { | |
res.push_back(Interval(start, end)); | |
start = intervals[i].start; | |
end = intervals[i].end; | |
} else if (intervals[i].end > end) { | |
end = intervals[i].end; | |
} | |
} | |
res.push_back(Interval(start, end)); | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment