同意! 如果像leetcode insert interval里区间vector已经排序,不用创建新vector, 只需 一步erase 和 insert, O(n) vector insert(vector &intervals, Interval newInterval) { auto start = intervals.begin(); auto it= start; for(; it !=intervals.end(); ++it) { if(newInterval.endstart) { //insert newinterval here //before insertion, erase prev intervals which are already merged to newinterval it = intervals.erase(start, it); intervals.insert(it, newInterval); return intervals; } else if (newInterval.start>it->end){ //newinterval has bigger start start++; } else { //cur interval and newinterval have overlap newInterval.start = min(it->start, newInterval.start); newInterval.end = max(it->end, newInterval.end); } }
if(start!=it) { //this is the case that newinterval includes all intervals it = intervals.erase(start, it); } intervals.insert(it, newInterval); return intervals;
} 如果区间vector没排序,就一个一个删 vector insert(vector &intervals, Interval newInterval) { auto it= intervals.begin(); for(; it !=intervals.end(); ) { if(newInterval.endstart||newInterval.start>it->end) { it++; } else { //cur interval and newinterval have overlap newInterval.start = min(it->start, newInterval.start); newInterval.end = max(it->end, newInterval.end); it = intervals.erase(it); } } intervals.insert(it, newInterval); return intervals;