[LeetCode] Insert Interval

vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
	int beg = intervals.size(), end = intervals.size()-1;
	bool getBeg = false;
	for (int i = 0; i < intervals.size(); i++)
	{
		if (newInterval.start <= intervals[i].start)
		{
			if (!getBeg)
			{
				beg = i;
				getBeg = true;
			}
		}
		else if (intervals[i].start < newInterval.start && newInterval.start <= intervals[i].end)
		{
			newInterval.start = intervals[i].start;
			if (!getBeg)
			{
				beg = i;
				getBeg = true;
			}
		}
		if (newInterval.end < intervals[i].start)
		{
			end = i - 1;
			break;
		}
		if (newInterval.end >= intervals[i].start && newInterval.end <= intervals[i].end)
		{
			newInterval.end = intervals[i].end;
			end = i;
			break;
		}
	}
	if (end == -1)
	{
		intervals.insert(intervals.begin(), newInterval);
		return intervals;
	}
	if (beg == intervals.size())
	{
		intervals.push_back(newInterval);
		return intervals;
	}
	intervals.erase(intervals.begin()+beg, intervals.begin()+end+1);
	intervals.insert(intervals.begin()+beg, newInterval);
	return intervals;

}

你可能感兴趣的:(LeetCode,刷题)