-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathInsert Interval.cpp
More file actions
39 lines (36 loc) · 1.06 KB
/
Insert Interval.cpp
File metadata and controls
39 lines (36 loc) · 1.06 KB
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
/*
1 pass the intervals of end < newInterval.start
2 merge newInterval with those of start <= newInterval.end
3 push newInterval
4 pass the rest intervals
what if the intervals are not sorted?
*/
/**
* 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;
int n = intervals.size();
int i = 0;
for (; i<n && intervals[i].end < newInterval.start; i++){
res.push_back(intervals[i]);
}
for (; i<n && intervals[i].start <= newInterval.end; i++){
newInterval.start = min(newInterval.start, intervals[i].start);
newInterval.end = max(newInterval.end, intervals[i].end);
}
res.push_back(newInterval);
for (; i<n; i++){
res.push_back(intervals[i]);
}
return res;
}
};