[LeetCode] Merge Intervals

vector<Interval> merge(vector<Interval> &intervals) {
	vector<Interval> merge;
	int n = intervals.size();
	if(n < 1)
	{
		return merge;
	}

	merge.push_back(intervals[0]);    
	for(int i = 1; i < n; i++)
	{
		vector<int> bound;
		for(int i = 0; i < merge.size(); i++)
		{
			bound.push_back(merge[i].start);
			bound.push_back(merge[i].end);
		}

		Interval interval = intervals[i];                      

		if(interval.end < bound[0])
		{
			merge.insert(merge.begin(), interval);
			continue;
		}
		int lastIndex = bound.size() - 1; 
		if(interval.start > bound[lastIndex])
		{
			merge.push_back(interval);
			continue;
		}

		int left,right;
		for(int i = 0; i <= lastIndex; i++)
		{
			if(interval.start <= bound[i])
			{
				left = i - 1;
				break;
			}
		}
		for(int i = lastIndex; i >= 0; i--)
		{
			if(interval.end >= bound[i])
			{
				right = i;
				break;
			}
		}

		Interval newInterval;
		int merge_beg = (left+1)/2, merge_end = right/2;            
		if(left%2 == 0)
		{
			newInterval.start = merge[merge_beg].start;
		}
		else 
		{
			newInterval.start = interval.start;
		}
		if(right%2 == 0)
		{
			newInterval.end = merge[merge_end].end;
		}
		else
		{
			newInterval.end = interval.end;
		}
		merge.erase(merge.begin()+merge_beg, merge.begin()+merge_end+1);
		merge.insert(merge.begin()+merge_beg, newInterval);             
	}
	return merge;           
}
写得太复杂了,感觉应该有更好的方法。

你可能感兴趣的:([LeetCode] Merge Intervals)