-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLeetCode#46.cc
50 lines (48 loc) · 1.61 KB
/
LeetCode#46.cc
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
/**
* 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> &ints, Interval newInt) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool isFinish = false;
int n = ints.size();
vector<Interval> ret;
for(int i=0;i<n;i++)
if(isFinish)
ret.push_back(ints[i]);
else{
if(newInt.start <= ints[i].end){
if(newInt.end < ints[i].start){
ret.push_back(newInt);
ret.push_back(ints[i]);
isFinish=true;
}
else{
int left = newInt.start < ints[i].start ? newInt.start:ints[i].start;
int right= newInt.end > ints[i].end ? newInt.end : ints[i].end;
int j = i+1;
while(j<n&&ints[j].start<=right){
if(ints[j].end>right) right = ints[j].end;
j++;
}
ret.push_back(Interval(left,right));
isFinish=true;
i=j-1;
}
}
else{
ret.push_back(ints[i]);
}
}
if(!isFinish) ret.push_back(newInt);
return ret;
}
};