Merge Intervals

Posted ymjyqsx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Merge Intervals相关的知识,希望对你有一定的参考价值。

static作用:https://www.cnblogs.com/songdanzju/p/7422380.html

 

/**
 * 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> result;
        int length = intervals.size();
        if(length <= 0)
            return result;
        sort(intervals.begin(),intervals.end(),cmp);
        result.push_back(intervals[0]);
        for(int i = 1;i < length;i++){
            int st = intervals[i].start;
            int en = intervals[i].end;
            if(st <= result.back().end){
                Interval tmp(result.back().start,en);
                if(en >= result.back().end){
                    result.pop_back();
                    result.push_back(tmp);
                }
                else
                    continue;
            }
            else
                result.push_back(intervals[i]);
        }
        return result;
    }
    static bool cmp(Interval a,Interval b){
        return a.start < b.start;
    }
};

 

以上是关于Merge Intervals的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 56. Merge Intervals

#Leetcode# 56. Merge Intervals

56. Merge Intervals - LeetCode

56. Merge Intervals

#56 Merge intervals

56. Merge Intervals 57. Insert Interval *HARD*