Lintcode30 Insert Interval solution 题解

来源:互联网 发布:mac系统杀毒软件 编辑:程序博客网 时间:2024/05/16 19:24

【题目描述】

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 0
原创粉丝点击