Similar to merge intervals. But this is easier than merge interval, because every side is kind of "sorted".
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { 13 vector<Interval> result; 14 if (intervals.size() == 0) { 15 result.push_back(newInterval); 16 return result; 17 } 18 queue<int> left, right; 19 int len = intervals.size(); 20 bool lf = true, rf = true; 21 for (int i = 0; i < len; i++) { 22 if (lf && newInterval.start < intervals[i].start) { 23 left.push(newInterval.start); 24 lf = false; 25 } 26 if (rf && newInterval.end < intervals[i].end) { 27 right.push(newInterval.end); 28 rf = false; 29 } 30 left.push(intervals[i].start); 31 right.push(intervals[i].end); 32 } 33 if (lf) left.push(newInterval.start); 34 if (rf) right.push(newInterval.end); 35 while (!left.empty()) { 36 int s = left.front(), e = right.front(); 37 left.pop(), right.pop(); 38 while (!left.empty()) { 39 if (e >= left.front()) { 40 e = right.front(); 41 left.pop(), right.pop(); 42 } else break; 43 } 44 result.push_back(Interval(s, e)); 45 } 46 return result; 47 } 48 };
时间: 2024-10-05 16:36:29