千家信息网

Lintcode30 Insert Interval solution 题解

发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,题目描述】Given a non-overlapping interval list which is sorted by start point.Insert a new interval into
千家信息网最后更新 2024年09月22日Lintcode30 Insert Interval solution 题解

题目描述】

Given a non-overlapping interval list which is sorted by start point.Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

给出一个无重叠的按照区间起始端点排序的区间列表。在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

【题目链接】

http://www.lintcode.com/en/problem/insert-interval/

【题目解析】

用pos记录newInterval应该插入的位置。顺序遍历intervals中的元素,若当前interval的end比newInterval的start还小,则将当前interval加入答案,同时pos+1;若比newInterval大,则直接加入答案;若有overlap,则需要merge,newInterval的start取两者间小的,end取两者间大的。最后在pos的位置插入newInterval即可。

【参考答案】

http://www.jiuzhang.com/solutions/insert-interval/


0