LeetCode 57. Insert Interval
Solution1:我的答案
算法很简单,不知道为何会被标记为hard题目
/**
* Definition for an interval.
* 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> res;
int i = 0;
// pre
for (; i < intervals.size(); i++) {
if (intervals[i].end < newInterval.start) {
res.push_back(intervals[i]);
} else
break;
}
int new_start = newInterval.start, new_end = newInterval.end;
for (; i < intervals.size(); i++) {
if (!(newInterval.start > intervals[i].end
|| newInterval.end < intervals[i].start)) {
new_start = min(new_start, intervals[i].start);
new_end = max(new_end, intervals[i].end);
} else
break;
}
Interval temp = Interval(new_start, new_end);
res.push_back(temp);
//post
for (; i < intervals.size(); i++)
res.push_back(intervals[i]);
return res;
}
};