码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_56insert [Insert Interval]

时间:2014-07-24 12:32:05      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:io   art   re   c   ar   new   amp   window   

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

标签:io   art   re   c   ar   new   amp   window   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!