-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insert Interval.cpp
46 lines (42 loc) · 1.29 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
/**
* 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> res;
bool isInsert=false;
for (auto a:intervals){
if (isInsert){
res.push_back(a);
}
else if (newInterval.end < a.start){
isInsert=true;
res.push_back(newInterval);
res.push_back(a);
}
else if (overlap(newInterval,a)){
newInterval.start = min(newInterval.start,a.start);
newInterval.end = max(newInterval.end,a.end);
}
else res.push_back(a);
}
if (!isInsert) res.push_back(newInterval);
return res;
}
bool overlap(Interval a, Interval b){
if (a.start>b.start){
Interval temp=b;
b=a;
a=temp;
}
if (a.end >= b.start) return true;
else return false;
}
};