LeetCode#56. Merge Intervals

  • Title: Combine a system of intervals, such as [1,3],[2,6],[8,10],[15,18] into [1,6],[8,10],[ 15,18]
  • Difficulty: Medium
  • Idea: sort the interval intervals according to the start time, and then compare the end time of the current interval and the start time of the next time interval to determine whether the two intervals can be merged.
  • Code:
/**
 * 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> res;
        if(intervals.empty()){
            return res;
        }
        sort(intervals.begin(),intervals.end(),increaseSort);//升序排序
        Interval interval = intervals[0];
        for(int i = 1; i < intervals.size(); i++){
            if(interval.end >= intervals[i].start){
                interval.end = max(interval.end,intervals[i].end);
            }else{
                res.push_back(interval);
                interval = intervals[i];
            }
        }
        res.push_back(interval);
        return res;
    }
    static bool increaseSort(Interval v1, Interval v2){
        return v1.start < v2.start;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606723&siteId=291194637