-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertinterval.cpp
More file actions
56 lines (54 loc) · 1.39 KB
/
insertinterval.cpp
File metadata and controls
56 lines (54 loc) · 1.39 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
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 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();
ret.clear();
if (len == 0)
{
ret.push_back(newInterval);
return ret;
}
bool flag = false;
for (auto x : intervals)
{
if (x.end < newInterval.start)
{
ret.push_back(x);
}
else if (x.start > newInterval.end)
{
if (flag == false)
{
ret.push_back(newInterval);
flag = true;
}
ret.push_back(x);
}
else if (x.start > newInterval.start && x.end < newInterval.end)
{
continue;
}
else
{
newInterval.start = min(x.start, newInterval.start);
newInterval.end = max(x.end, newInterval.end);
}
}
if (flag == false)
{
ret.push_back(newInterval);
}
return ret;
}
private:
vector<Interval>ret;
};