Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 11:57
Show Gist options
  • Select an option

  • Save pdu/4971191 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971191 to your computer and use it in GitHub Desktop.
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]. http://leetcode.com/onlinejudge#question_56
/**
* 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(const Interval& a, const Interval& b) {
if (a.start != b.start)
return a.start < b.start;
else
return a.end < b.end;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> ans;
int n = intervals.size();
sort(intervals.begin(), intervals.end(), cmp);
int pos = 0;
while (pos < n) {
int npos;
int nend = intervals[pos].end;
for (npos = pos + 1; npos < n; ++npos) {
if (nend < intervals[npos].start) {
break;
}
if (nend < intervals[npos].end) {
nend = intervals[npos].end;
}
}
Interval tmp(intervals[pos].start, nend);
ans.push_back(tmp);
pos = npos;
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment