其他分享
首页 > 其他分享> > LeetCode | 56. Merge Intervals

LeetCode | 56. 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.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

 

代码:

/**
 * 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:
    static bool cmp(const Interval& a, const Interval& b) {
        if(b.start < a.start)
            return false;
        if(b.start == a.start)
            if(b.end <= a.end)
                return false;
            else
                return true;
		return true;
	}
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> merged;
		if(intervals.size() < 1)
			return merged;
		sort(intervals.begin(), intervals.end(), cmp);
		merged.push_back(intervals[0]);
		int idx = 0;
		for(int i = 1; i<intervals.size(); i++)
		{
			if(intervals[i].start >= merged[idx].start && intervals[i].start <= merged[idx].end)
			{
				merged[idx].start = min(merged[idx].start, intervals[i].start);
				merged[idx].end = max(merged[idx].end, intervals[i].end);
			}
			else
			{
				merged.push_back(intervals[i]);
				idx++;
			}
		}
		return merged;
    }
};

 

 

 

 

标签:Interval,end,start,int,56,Merge,intervals,LeetCode,merged
来源: https://blog.csdn.net/iLOVEJohnny/article/details/100165428