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]
.
[Analysis]
唯一需要注意的时,cmp函数需要写在Solution类外面。
[Solution]
//
// Definition for an interval.
// struct Interval {
// int start;
// int end;
// Interval() : start(0), end(0) {}
// Interval(int s, int e) : start(s), end(e) {}
// };
//
// compare
bool cmp(const Interval &inte1, const Interval &inte2){
return inte1.start < inte2.start;
}
// definition of Solution
class Solution {
public:
// check the two intervals wether they are interlocked
bool check(Interval inter1, Interval inter2){
if((inter1.start >= inter2.start && inter1.start <= inter2.end) || (inter1.end >= inter2.start && inter1.end <= inter2.end)){
return true;
}
else if((inter2.start >= inter1.start && inter2.start <= inter1.end) || (inter2.end >= inter1.start && inter2.end <= inter1.end)){
return true;
}
else{
return false;
}
}
// merge the two intervals
Interval merge(Interval inter1, Interval inter2){
Interval inter;
inter.start = inter1.start < inter2.start ? inter1.start : inter2.start;
inter.end = inter1.end > inter2.end ? inter1.end : inter2.end;
return inter;
}
// merge
vector<Interval> merge(vector<Interval> &intervals) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<Interval> res;
// sort
sort(intervals.begin(), intervals.end(), cmp);
for(int i = 0; i < intervals.size(); ++i){
Interval inte = intervals[i];
if(res.size() > 0 && check(res.back(), inte)){
while(res.size() > 0 && check(res.back(), inte)){
inte = merge(res.back(), intervals[i]);
res.pop_back();
}
}
res.push_back(inte);
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客