forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert-interval(AC).cpp
More file actions
41 lines (40 loc) · 1.03 KB
/
insert-interval(AC).cpp
File metadata and controls
41 lines (40 loc) · 1.03 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
#include <algorithm>
using namespace std;
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
class Solution {
public:
/**
* Insert newInterval into intervals.
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> &a = intervals;
Interval b = newInterval;
int i, n = a.size();
vector<Interval> ans;
i = 0;
while (i < n && a[i].end < b.start) {
ans.push_back(a[i++]);
}
while (i < n && b.end >= a[i].start) {
b.start = min(b.start, a[i].start);
b.end = max(b.end, a[i].end);
++i;
}
ans.push_back(b);
while (i < n) {
ans.push_back(a[i++]);
}
return ans;
}
};