-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathInsert Interval.cpp
More file actions
44 lines (43 loc) · 1.08 KB
/
Insert Interval.cpp
File metadata and controls
44 lines (43 loc) · 1.08 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
39
40
41
42
43
44
/**
* 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:
static bool cmp(const Interval& left, const Interval& right)
{
return (left.start < right.start);
}
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval)
{
vector<Interval> result(intervals);
result.push_back(newInterval);
if (!result.empty())
{
sort(result.begin(), result.end(), cmp);
auto it1 = result.begin();
auto it2 = it1 + 1;
for (; it2 != result.end(); ++it2)
{
if (it2->start <= it1->end)
{
it1->end = max(it1->end, it2->end);
}
else
{
++it1;
*it1 = *it2;
}
}
++it1;
result.erase(it1, result.end());
}
return result;
}
};