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

 

 

 

 

上一篇:LeetCode | 57. Insert Interval


下一篇:DataNode的工作机制