Created
February 17, 2013 11:57
-
-
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
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
| /** | |
| * 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