-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path57-insert-interval.cpp
72 lines (67 loc) · 2.87 KB
/
57-insert-interval.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// thought of binary search bt compaction process is o(n). SO not applicable.
// class Solution {
// public:
// vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
// int left = 0;
// int right = size(intervals) - 1;
// while(left < right) {
// auto mid = left + (right - left) / 2;
// if (newInterval[0] < intervals[mid][0]) right = mid;
// else left = mid + 1;
// }
// if (left) {
// if (intervals[left - 1][1] >= newInterval[0]) {
// intervals[left - 1][1] = max(newInterval[1], intervals[left - 1][1]);
// int compaction = left;
// while(compaction < size(intervals) && intervals[left - 1][1] >= intervals[compaction][0]) {
// intervals[left - 1][1] = max(intervals[compaction][1], intervals[left - 1][1]);
// intervals[compaction++] = {-1, -1};
// }
// } else intervals.insert(intervals.begin() + left, newInterval);
// } else intervals.insert(intervals.begin() , newInterval);
// int j = 0;
// for(int i = 0 ; i < size(intervals); i++) {
// if (intervals[i][0] == -1 && intervals[i][1] == -1) continue;
// intervals[j++] = intervals[i];
// }
// intervals.resize(j);
// return intervals;
// }
// };
// class Solution {
// public:
// vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
// vector<vector<int>> res;
// bool populating = false;
// bool inserted = false;
// for(auto curr: intervals) {
// if (newInterval[0] <= curr[1] && newInterval[1] >= curr[0]) {
// newInterval[0] = min(newInterval[0], curr[0]);
// newInterval[1] = max(newInterval[1], curr[1]);
// populating = true;
// } else {
// if (populating) { res.push_back(newInterval); populating = false; inserted = true; }
// res.push_back(curr);
// }
// }
// if (populating || !inserted) { res.push_back(newInterval); inserted = true; }
// return res;
// }
// };
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
int n = intervals.size(), i = 0; bool available = true;
while (i < n || available) {
vector<int> cur;
if (available && (i == n || newInterval[0] < intervals[i][0])) {
cur = newInterval;
available = false;
} else cur = intervals[i++];
if (!res.size() || res.back()[1] < cur[0]) res.push_back(cur);
else res.back()[1] = max(res.back()[1], cur[1]);
}
return res;
}
};