[leetcode] 区间合并问题 Merge Interval

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].

来源:leetcode

思路:用贪心法,先按照每个区间的start position进行排序,排序之后进行合并。代码如下:

/**
 * 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) {
        int i=0;
        if(intervals.size() >1)
            for(int i=1; i< intervals.size(); i++) //进行排序
            {
                Interval inte = intervals[i];
                int j;
                for(j=i-1; j>=0; j--)
                {
                    if(inte.start< intervals[j].start )
                        intervals[j+1] = intervals[j];
                    else
                        break;
                }
                intervals[j+1] = inte;
            }
        else
            return intervals;
            
        vector<Interval> out;
        out.push_back(intervals[0]);
        
        for(int i=1; i< intervals.size(); i++)
        {
            if( out.back().end >= intervals[i].start )
                out.back().end = max( intervals[i].end, out.back().end );
            else
                out.push_back( intervals[i] );
        }
        
        return out;
    }
};


你可能感兴趣的:([leetcode] 区间合并问题 Merge Interval)