标签:
There are mainly two solutions to this problem. The first one is of O(n) time. Its idea is to compare each interval in intervals (intervals[i]) with newInterval and then perform respective operations according to their relative locations.
The code is as follows.
1 class Solution { 2 public: 3 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { 4 vector<Interval> res; 5 int n = intervals.size(); 6 for (int i = 0; i < n; i++) { 7 if (!isOverlap(intervals[i], newInterval)) { 8 if (intervals[i].end < newInterval.start) 9 res.push_back(intervals[i]); 10 else { 11 res.push_back(newInterval); 12 for (int j = i; j < n; j++) 13 res.push_back(intervals[j]); 14 return res; 15 } 16 } 17 else newInterval = merge(intervals[i], newInterval); 18 } 19 res.push_back(newInterval); 20 return res; 21 } 22 private: 23 bool isOverlap(Interval interval1, Interval interval2) { 24 return !(interval1.start > interval2.end || interval2.start > interval1.end); 25 } 26 Interval merge(Interval interval1, Interval interval2) { 27 int start = min(interval1.start, interval2.start); 28 int end = max(interval1.end, interval2.end); 29 return Interval(start, end); 30 } 31 };
The second solution is of O(logn) and will come out soon...
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4625034.html