码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode30 Insert Interval solution 题解

时间:2017-05-08 14:41:02      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:necessary   solution   start   记录   元素   

题目描述】

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/


Lintcode30 Insert Interval solution 题解

标签:necessary   solution   start   记录   元素   

原文地址:http://12799252.blog.51cto.com/12789252/1922961

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!