• ``````/**
* 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 {
public:

vector<Interval> merge(vector<Interval>& intervals) {
vector<bool> used;
used.resize(intervals.size());
for(int i = 0; i < intervals.size(); i++)
{
used[i] = false;
}
sort(intervals.begin(), intervals.end(), comp);
vector<Interval> ret;
for (int i = 0; i < intervals.size(); i++) {
if (!used[i]) {
used[i] = true;
for(int j = i+1; j < intervals.size();j++)
{
if(!used[j])
{
if(CanMerge(intervals[i], intervals[j]))
{
MergeTwo(intervals[i], intervals[j]);
used[j] = true;
}
else
{
break;
}
}
}
ret.push_back(intervals[i]);
}

}
return ret;
}

bool CanMerge(struct Interval & a, struct Interval & b)
{
if(a.start < b.start)
{
if(b.start <= a.end)
{
return true;
}
}
else
{
if(a.start <= b.end )
{
return true;
}
}
return false;
}
void MergeTwo(struct Interval & a, struct Interval & b)
{
if(a.start < b.start)
{
if(b.end > a.end)
{
a.end = b.end;
}
}
else
{
a.start = b.start;
if( a.end < b.end)
{
a.end = b.end;
}
}
}

static bool comp(struct Interval & a, struct Interval & b)
{
if(a.start <= b.start)
{
return true;
}
else
{
return false;
}
}
};
``````