Skip to content

56. Merge Intervals

难度:Medium

刷题内容

原题连接

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


回到顶部