56. Merge Intervals (Array; Sort)

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

注意点:

1。并不是像例子中给出的那样,前一个interval必定在后一个interval的前边。

所以我们先要对start进行排序。必须把start小的放在前面,然后按序递增,否则会出现这样的错误

Input:[[2,3],[4,5],[6,7],[8,9],[1,10]]
Output:[[2,3],[4,5],[6,7],[1,10]]
Expected:[[1,10]]
 
2。sort start需要自定义compare函数,注意升序的时候不能定义<=,否则会造成Time Limit Exceeded
原因是sort的compare函数必须满足strict weak ordering。时间复杂度O(nlogn), reference: http://www.cplusplus.com/reference/list/list/sort/
 
3。两个字串长度和 =各子串长度相加的时候,如下例,并没有overlap。仅当[1,4],[4,6]才有overlap。 
[[1,4],[5,6]]
Output:[[1,6]]
Expected:[[1,4],[5,6]]
/**
 * 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 compare(Interval v1, Interval v2)
    {
        if(v1.start < v2.start)
            return true;
        else if(v1.start > v2.start)
            return false;
        else
            return v1.end < v2.end;
    }
    
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> result;
        if(intervals.empty()) return result;
        
        sort(intervals.begin(),intervals.end(),compare);
        result.push_back(intervals[0]);
        for(int i = 1; i < intervals.size(); i++){
            if(result[result.size()-1].end >= intervals[i].end) //totally contain
                continue;
                
            if(result[result.size()-1].end >= intervals[i].start){//there's overlap
                result[result.size()-1].end = intervals[i].end;
            }
            else{ //there's no overlap
                result.push_back(intervals[i]);
            }
        }
        
        return result;
    }
};

 

 

posted on 2015-12-05 10:35  joannae  阅读(139)  评论(0编辑  收藏  举报

导航