首页 > 其他 > 详细

LeetCode_56insert [Insert Interval]

时间:2014-07-24 12:32:05      阅读:293      评论:0      收藏:0      [点我收藏+]
#pragma warning(disable:4996)

#include <Windows.h>
#include <tchar.h>
#include <cstdio>
#include <vector>
using namespace std;

/*
	submit time : 1
	request :
		Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

		You may assume that the intervals were initially sorted according to their start times.

		Example 1:
		Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

		Example 2:
		Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

		This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
*/

struct Interval {
	int start;
	int end;
	Interval() : start(0), end(0) {}
	Interval(int s, int e) : start(s), end(e) {}
};

vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
	vector<Interval> res;
	int length = intervals.size(), newStart = newInterval.start;

	int i = 0;
	while (i < length && intervals[i].start <= newStart) 
		res.push_back(intervals[i++]);
	// insert newInterval
	int size = res.size();
	if (size == 0) {
		i = 0;
		res.push_back(newInterval);
	}
	else {
		if (res[size - 1].end >= newInterval.start)
			res[size - 1].end = max(res[size - 1].end, newInterval.end);
		else
			res.push_back(newInterval);
	}
	// insert the left
	while (i < length) {
		size = res.size();
		if (res[size - 1].end >= intervals[i].start) {
			res[size - 1].end = max(res[size - 1].end, intervals[i].end);
			++i;
		}
		else
			res.push_back(intervals[i++]);
	}

	return res;
}



LeetCode_56insert [Insert Interval],布布扣,bubuko.com

LeetCode_56insert [Insert Interval]

原文:http://my.oschina.net/ITHaozi/blog/294415

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!