此题主要需要注意的是先将结构体数组进行排序,需要改写compare函数
代码
bool compare(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> res;
int size = intervals.size();
if(size==0)
return res;
sort(intervals.begin(), intervals.end(), compare);
res.push_back(intervals[0]);
for(int i = 1; i < size; ++i)
{
Interval &top = res[res.size()-1];
if(intervals[i].start <= top.end)
{
if(intervals[i].end > top.end)
top.end = intervals[i].end;
}
else
{
res.push_back(intervals[i]);
}
}
return res;
}
};