-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path057_Insert_Interval.cpp
More file actions
27 lines (27 loc) · 866 Bytes
/
Copy path057_Insert_Interval.cpp
File metadata and controls
27 lines (27 loc) · 866 Bytes
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
class Solution {
class cmp{
public:
inline bool operator()(const Interval& a, const Interval& b) const {
return (a.start == b.start) ? (a.end < b.end) : (a.start < b.start);
}
};
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
ans.clear();
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), cmp());
int k = 0;
while(k < intervals.size()) {
Interval tmp;
int st = intervals[k].start, ed = intervals[k].end;
while(k + 1 < intervals.size() && ed >= intervals[k + 1].start)
ed = max(ed, intervals[++k].end);
tmp.start = st, tmp.end = ed;
ans.push_back(tmp);
k++;
}
return ans;
}
private:
vector<Interval> ans;
};