Skip to content

Instantly share code, notes, and snippets.

@hyfrey
Created October 4, 2012 07:51
Show Gist options
  • Save hyfrey/3832054 to your computer and use it in GitHub Desktop.
Save hyfrey/3832054 to your computer and use it in GitHub Desktop.
leetcode Merge Intervals
/*
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