Leetcod Insert Interval,记当前遍历的区间为cur,新区间为new本题主要是对几种情况的考虑,主要如有:
- cur.start > new.end,此时cur与new完全独立,可以直接push,但是new在cur前
- cur.start = new.end,此时cur与new可以连接起来,此时造一个新元素,并push
- cur.start >= new.start and cur.end >= new.end,此时两个元素需要合并成一个,合并后的元素为[new.start, cur.end],并push
- cur.start <= new.start and cur.end >= new.end,此时new被cur包含,直接push元素new
- cur.start <= new.start and cur.end < new.end,此时new的下限更改成cur的下限,继续后面的遍历
- cur与new不相交,且new大于cur,直接push cur
- 元素new已经处理完成,后续元素直接copy到新的数组中
- 若在最后new还没有处理,直接push new到数组
相关代码如下,算法时间复杂度为o(n):
#include<iostream>
#include<vector>
using namespace std;
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>& intervals, Interval newInterval) {
vector<Interval> re;
bool flag = true;
for (int i = 0; i < intervals.size(); i++) {
if (flag) {
if (intervals[i].start >= newInterval.end) {
flag = false;
if (intervals[i].start > newInterval.end) {
// condition a
re.push_back(newInterval);
re.push_back(intervals[i]);
} else {
// condition b
newInterval.end = intervals[i].end;
re.push_back(newInterval);
}
} else if (intervals[i].start >= newInterval.start) {
if (intervals[i].end >= newInterval.end) {
// condition c
newInterval.end = intervals[i].end;
re.push_back(newInterval);
flag = false;
}
} else if (intervals[i].end >= newInterval.start) {
if (intervals[i].end >= newInterval.end) {
// condition d
flag = false;
re.push_back(intervals[i]);
} else {
// condition e
newInterval.start = intervals[i].start;
}
} else if (intervals[i].end < newInterval.start) {
// condition f
re.push_back(intervals[i]);
}
} else {
// condition g
re.push_back(intervals[i]);
}
}
if (flag) {
re.push_back(newInterval);
}
return re;
}
};
// Sample input: ./a.out numa_1 numa_2 numb_1 numb_2...
int main(int argc, char * argv[]) {
Solution so;
vector<Interval> test;
for (int i = 1; i < argc - 2; i += 2) {
test.push_back(Interval(atoi(argv[i]), atoi(argv[i + 1])));
}
Interval newInterval(atoi(argv[argc - 2]), atoi(argv[argc - 1]));
vector<Interval> re = so.insert(test, newInterval);
cout<<"re: ";
for (auto a: re) {
cout<<"["<<a.start<<", "<<a.end<<"] ";
}
cout<<endl;
return 0;
}
测试:./a.out 1 2 3 4 6 8 10 20 2 8
结果:re: [1, 8] [10, 20]