kiddy

Merge Intervals

leave a comment »

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

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */



bool compare(const Interval &a, const Interval &b){
    return a.start < b.start;
}


class Solution {
public:

    vector<Interval> merge(vector<Interval> &intervals) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<Interval> ret;
        ret.clear();
        int size = intervals.size();
        if(size == 0)   return ret;
        sort(intervals.begin(), intervals.end(), mycompare);        
        Interval pre = intervals[0];
        for(int i = 1; i <= size; i++){
            if(i == size){
                ret.push_back(pre);
                break;
            }
            Interval cur = intervals[i];
            if(pre.end >= cur.start){
                pre.end = max(cur.end, pre.end);//error: forget max
            }else{
                ret.push_back(pre);
                pre = cur;
            }
        }
        return ret;        
    }
};

Written by linzhongzl

April 30, 2013 at 9:50 pm

Posted in Leetcode

Leave a comment