Leetcode#57 Insert Interval
遍历每个区间intervals[i]:
如果intervals[i]在newInterval的左边,且没有交集,把intervals[i]插入result
如果intervals[i]在newInterval的右边,且没有交集,如果newInterval还没插入,则将newInterval插入result,之后再插入intervals[i]
如果intervals[i]和newInterval有交集,则更新newInterval的start、end
代码:
1 vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { 2 vector<Interval> result; 3 bool inserted = false; 4 5 for (auto itv : intervals) { 6 if (itv.end < newInterval.start) 7 result.push_back(itv); 8 else if (itv.start > newInterval.end) { 9 if (!inserted) { 10 result.push_back(newInterval); 11 inserted = true; 12 } 13 result.push_back(itv); 14 } 15 else { 16 newInterval.start = min(itv.start, newInterval.start); 17 newInterval.end = max(itv.end, newInterval.end); 18 } 19 } 20 if (!inserted) 21 result.push_back(newInterval); 22 23 return result; 24 }