Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created October 29, 2013 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/7217367 to your computer and use it in GitHub Desktop.
Save eclipselu/7217367 to your computer and use it in GitHub Desktop.
/**
* 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 a, Interval b) {
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<Interval> res;
sort(intervals.begin(), intervals.end(), cmp);
int i = 0, len = intervals.size();
while(i < len) {
int j = i + 1;
Interval tmp(intervals[i].start, intervals[i].end);
while (j < len && intervals[j].start <= tmp.end) {
tmp.end = std::max(intervals[j].end, tmp.end);
j++;
}
res.push_back(tmp);
i = j;
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment