首页 > 代码库 > Leetcode Insert Interval
Leetcode 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:
Given intervals [1,3],[6,9]
, insert and merge [2,5]
in as [1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as [1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
题目的意思:给定一个非重叠的区间,插入一个新的区间,如果区间与其他区间相交,则必须合并
注意题目有个假设,区间根据start时间进行了排序,所以自己不需要排序
struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {}};
解题思路:设给定的区间为intervals,插入的区间为newInterval,只需要将newInterval与intervals相交的区间合并即可,
如果newInterval与intervals没有相交的区间,则必须将newInterval插入到相应的位置
本题有三种情况
(1)如果intervals[i].end < newInterval.start,说明intervals[i]与newInterval不相交,保留即可
(2)如果intervals[i].start > newInterval.end, 说明intervals[i]与newInterval不相交,将newInterval插入即可,注意这时候其后面的intervals[i],都可以保留,这是由于本身区间是不想交的。
(3) 如果intervals[i].start < newInterval.end,说明区间相交,合并区间,更新newInterval
class Solution {public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> res; for(int i = 0 ; i < intervals.size(); ++ i){ if(intervals[i].end < newInterval.start) res.push_back(intervals[i]); else if(intervals[i].start > newInterval.end) { res.push_back(newInterval); newInterval = intervals[i]; }else if(intervals[i].start <= newInterval.end ){ newInterval.start = min(newInterval.start, intervals[i].start); newInterval.end = max(newInterval.end, intervals[i].end); } } res.push_back(newInterval); return res; }};