leetcodequestion_56 Merge Intervals

 

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

vector<Interval> merge(vector<Interval>& intervals) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

    	sort(intervals.begin(), intervals.end(), cmp);

		vector<Interval> res;

		vector<Interval>::iterator it = intervals.begin();

		Interval* cur = NULL;

		for(it; it != intervals.end(); ++it)

		{

            if(cur == NULL)

            {

                cur = &(*it);

				continue;

            }

			if((*cur).end < (*it).start)

			{

				res.push_back(*cur);

				cur = &(*it);

			}else{

				(*cur).end = (*cur).end > (*it).end ? (*cur).end : (*it).end;

			}

		}

		if(cur != NULL)

		res.push_back(*cur);

		return res;

    }





 

你可能感兴趣的:(LeetCode)