57. Insert Interval(插入区间)
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals =[[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval =[4,8]
Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval[4,8]
overlaps with[3,5],[6,7],[8,10]
.
左边不重叠: a[i][1] < new[0]
右边不重叠: a[i][0] > new[1] ---取反-->中间重叠 a[i][0] <= new[1]
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: i = 0 res = [] n = len(intervals) while i < n and intervals[i][1] < newInterval[0]: res.append(intervals[i]) i+=1 while i < n and intervals[i][0] <= newInterval[1]: newInterval[0] = min(newInterval[0],intervals[i][0]) newInterval[1] = max(newInterval[1],intervals[i][1]) i+=1 res.append(newInterval) while i < n : res.append(intervals[i]) i+=1 return res
class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { int n = intervals.size(); int i = 0; vector<vector<int>> res; while(i<n && intervals[i][1]<newInterval[0]) { res.emplace_back(intervals[i]); i++; } while(i <n && intervals[i][0] <=newInterval[1] ) { newInterval[0] = min(newInterval[0],intervals[i][0]); newInterval[1] = max(newInterval[1],intervals[i][1]); i++; } res.emplace_back(newInterval); for(;i<n;i++){ res.emplace_back(intervals[i]); } return res; } };
把要插入的元素插入,然后调用上一个题的merge
class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { intervals.emplace_back(newInterval); sort(intervals.begin(),intervals.end()); int s = 0, f = 0; vector<vector<int>> res; res.emplace_back(intervals[0]); for(int f = 1; f < intervals.size();f++) { auto& cur_node = res.back(); if (intervals[f][0] <= cur_node[1]) { cur_node[1] = max(cur_node[1],intervals[f][1]); } else { res.emplace_back(intervals[f]); } } return res; } };