-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.cpp
More file actions
45 lines (40 loc) · 1.19 KB
/
insert.cpp
File metadata and controls
45 lines (40 loc) · 1.19 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
#include <vector>
using namespace std;
class Solution
{
public:
vector<vector<int>> insert(vector<vector<int>> &intervals, vector<int> &newInterval)
{
vector<vector<int>> res;
if (intervals.empty()) return res;
// intervals已排序,所以我们不用再排序了
// 直接遍历这个排序好的数组,插入即可
for (int i = 0; i < intervals.size(); i++)
{
if (i + 1 > intervals.size()) break;
if (intervals[i][0] <= newInterval[0] && intervals[i + 1][0] >= newInterval[0])
{
intervals.insert(intervals.begin() + i + 1,newInterval);
break;
}
}
// 随后继续进行merge操作
res.push_back(intervals[0]);
for (int i = 1;i < intervals.size();i++)
{
if (res.back()[1] >= intervals[i][0])
{
res.back()[1] = max(res.back()[1],intervals[i][1]);
}
else res.push_back(intervals[i]);
}
return res;
}
private:
template<typename T>
T max(T num1,T num2)
{
if (num1 > num2) return num1;
else return num2;
}
};