Created
October 29, 2013 15:56
-
-
Save eclipselu/7217367 to your computer and use it in GitHub Desktop.
LeetCode: Merge Intervals http://oj.leetcode.com/problems/merge-intervals/
This file contains 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(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