Skip to content

Latest commit

 

History

History
executable file
·
62 lines (51 loc) · 1.69 KB

0056._Merge_Intervals.md

File metadata and controls

executable file
·
62 lines (51 loc) · 1.69 KB

56. Merge Intervals

难度:Medium

刷题内容

原题连接

内容描述

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;
    }
};