-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
67 lines (66 loc) · 1.55 KB
/
solution.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
67
/**
* 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)
{
int i = 0;
int len = intervals.size();
if(0 == len)
{
intervals.push_back(newInterval); return intervals;
}
vector<Interval> re;
//find the insert position of start.
while(i < len && intervals[i].end < newInterval.start)
{
re.push_back(intervals[i]);
++i;
}
//at the right,
if(i == len)
{
re.push_back(newInterval); return re;
}
int j = i;
//find the insert position of end.
while(j < len && intervals[j].end < newInterval.end)
{
++j;
}
Interval jion;
jion.start = min(intervals[i].start, newInterval.start);
if(j == len)
{
jion.end = newInterval.end;
re.push_back(jion);
return re;
}
if(newInterval.end < intervals[j].start)
{
--j;
jion.end = newInterval.end;
re.push_back(jion);
}
else
{
jion.end = intervals[j].end;
re.push_back(jion);
}
++j;
while(j < len)
{
re.push_back(intervals[j]);
++j;
}
return re;
}
};