-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_interval.cpp
45 lines (40 loc) · 1.3 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
/**
* 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 len = intervals.size();
vector<Interval> newIntervals;
if(len <= 0){
return newIntervals;
}
bool pushed = false;
for(int i = 0; i < len; i++){
if(intervals[i].end < newInterval.start){
newIntervals.push_back(intervals[i]);
continue;
}
if(intervals[i].start > newInterval.end){
if(!pushed){
newIntervals.push_back(newInterval);
pushed = true;
}
newIntervals.push_back(intervals[i]);
continue;
}
newInterval.start = newInterval.start < intervals[i].start ? newInterval.start : intervals[i].start;
newInterval.end = newInterval.end > intervals[i].end ? newInterval.end : intervals[i].end;
}
if(!pushed){
newIntervals.push_back(newInterval);
}
return newIntervals;
}
};