# 56. Merge Intervals

## 刷题内容

• https://leetcode.com/problems/merge-intervals/

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.


Ë¼Â·1 **- Ê±¼ä¸´ÔÓ¶È: O(nlgn)*- ¿Õ¼ä¸´ÔÓ¶È: O(1)***

ÕâÀïÎÒÃÇÒªÏÈ¶ÔÊý×é½øÐÐÅÅÐò£¬°´ÕÕstart½øÐÐÉýÐòÅÅÐò¡£½ÓÏÂÀ´¾Í±éÀúÅÅÐòºÃµÄÊý×é£¬Èç¹ý²»Ïà½»¾Í½«Á½¸öÇø¼ä¶¼´æÈëans¡£Èç¹ûÏà½»¾Í½«ºÏ²¢ºóµÄÇø¼äµÄ²¢Èëans¡£

/**
* 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<Interval> ans;
if(!intervals.size())
return ans;
sort(intervals.begin(),intervals.end(),[](Interval a, Interval b){return a.start < b.start;});
for(int i = 0;i < intervals.size() - 1;++i)
if(intervals[i + 1].start <= intervals[i].end)
{
intervals[i + 1].start = intervals[i].start;
intervals[i].end = max(intervals[i].end,intervals[i + 1].end);
intervals[i + 1].end = intervals[i].end;
}
else
ans.push_back(intervals[i]);
ans.push_back(intervals[intervals.size() - 1]);
return ans;
}
};


apachecn/AiLearning