Created
April 6, 2017 15:21
-
-
Save s4553711/403072d9ff66a2a5d84a52e925603773 to your computer and use it in GitHub Desktop.
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) {} | |
* }; | |
*/ | |
class Solution { | |
static bool comp(Interval x, Interval y) { | |
return x.start < y.start || (x.start == y.start && x.end < y.end); | |
} | |
public: | |
vector<Interval> merge(vector<Interval>& intervals) { | |
vector<Interval> result; | |
if (intervals.size() == 0) return result; | |
sort(intervals.begin(), intervals.end(), Solution::comp); | |
int n_st = intervals[0].start, n_end = intervals[0].end; | |
for(int i = 1; i < intervals.size(); i++) { | |
if (intervals[i].start <= n_end) { | |
if (intervals[i].end > n_end) | |
n_end = intervals[i].end; | |
} else { | |
result.push_back(Interval(n_st, n_end)); | |
n_st = intervals[i].start, n_end = intervals[i].end; | |
} | |
} | |
result.push_back(Interval(n_st, n_end)); | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment