-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insert Interval.cpp
66 lines (66 loc) · 1.61 KB
/
Insert Interval.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> result;
int reader = 0, writer = 0;
bool inserted = false;
if (intervals.size() < 1)
{
result.push_back(newInterval);
return result;
}
if (intervals[0].start < newInterval.start)
{
result.push_back(intervals[0]);
}
else
{
result.push_back(newInterval);
inserted = true;
}
while (reader < intervals.size())
{
if (!inserted)
{
if (newInterval.start <= result[writer].end)
{
result[writer].end = max(result[writer].end, newInterval.end);
inserted = true;
}
else if (newInterval.start < intervals[reader].start)
{
result.push_back(newInterval);
writer++;
inserted = true;
}
}
if (intervals[reader].start <= result[writer].end)
{
result[writer].end = max(result[writer].end, intervals[reader].end);
}
else
{
result.push_back(intervals[reader]);
writer++;
}
reader++;
}
if (!inserted)
{
if (newInterval.start <= result[writer].end)
result[writer].end = max(result[writer].end, newInterval.end);
else
result.push_back(newInterval);
}
return result;
}
};