sundeepblue
4/27/2014 - 3:36 PM

merge intervals

merge intervals

// a compact version! 8/2/2015

    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> result;
        if (intervals.empty()) return result;
        sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b) {  // p1, should use const and & to speed up!!!!!
            return a.start < b.start; 
        });
        
        result.push_back(intervals[0]);
        for (int i=1; i<intervals.size(); i++) {
            Interval intv = intervals[i];
            if (result.back().end < intv.start)
                result.push_back(intv);
            else result.back().end = max(result.back().end, intv.end);
        }
        return result;
    }




struct interval {
    int start, end;
    interval(int s, int e) : start(s), end(e) {}
};
 
vector<interval> merge(vector<interval> &intvs) {
	if(intvs.empty()) 
		return intvs;
 
	sort(intvs.begin(), intvs.end(), [](const interval &v1, const interval &v2) { // gist1, should add const
		return v1.start < v2.start;
	});
	
	auto is_intersect = [] (const interval &v1, const interval &v2) { // gist, should add const
		if(v1.end < v2.start || v1.start > v2.end) return false;
		return true;
	};
 
	vector<interval>::iterator cur = intvs.begin();
    vector<interval>::iterator nxt;
    while(cur != intvs.end()) {
		nxt = cur+1;                                    // gist, cannot write as nxt = cur++;
		while(nxt != intvs.end() && is_intersect(*cur, *nxt)) {
			int begin = min(cur->start, nxt->start);
			int end = max(cur->end, nxt->end);
			cur->start = begin;
			cur->end = end;
			intvs.erase(nxt);
			nxt = cur++;
		}
		cur++;
	}
	return intvs;
}
 
int main() {
    vector<interval> vi = {{1,3}, {2,3}, {4,5}};
    vector<interval> res = merge(vi);
    for(auto i : res) 
        cout << i.start << ", " << i.end << endl;
}