Leetcode Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

 题目的意思是将相交得区间合并,典型的贪心算法

首先将区间先按照start进行排序,

然后保存先前区间的start和end

如果当前的start > 先前的end,说明当前的区间与之前的区间不想交,则将先前的区间放入结果中,同时更新start和end

如果当前的start < 先前的end,说明当前的区间与先前的区间相交,故比较当前的end与先前的end,如果当前的end大于先前的end,则更新先前的end为当前的end

bool cmp(const Interval& a, const Interval& b){
    if(a.start!=b.start) return a.start < b.start;
    else return a.end < b.end;
}

class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        sort(intervals.begin(), intervals.end(), cmp);
        vector<Interval> res;
        if(intervals.size() == 0) return res;
        int start = intervals[0].start, end = intervals[0].end;
        for(int i = 1 ; i <  intervals.size(); ++ i){
            if(intervals[i].start > end){
                res.push_back(Interval(start,end));
                start = intervals[i].start, end = intervals[i].end;
            }else{
                end = max(end, intervals[i].end);
            }
        }
        res.push_back(Interval(start,end));
        return res;
    }
};
 
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3825951.html