插入间隔不相交的区间排序列表区间、间隔、列表

2023-09-11 23:13:28 作者:思念像潮水丶不可阻挡

我有不相交的区间排序列表和一个间隔,如[(1,5),(10,15),(20,25)]和​​(12,27)。所以,(12,27)是间隔    我想将它们合并成不相交的区间排序列表:[(1,5),(10,27)。

I have a sorted list of disjoint intervals and an interval, e.g. [(1, 5), (10, 15), (20, 25)] and (12, 27). So, (12,27) is the interval I want to merge them into a sorted list of disjoint intervals: [(1, 5), (10, 27)].

推荐答案

伪:

list = ...
u = (12,27)
i = 0
newlist = []

while (max(list[i]) < min(u))  //add all intervals before intersection
  newlist.add(list[i++])
mini = i

while (min(list[i]) < max(u))  // skip all intersecting intervals
  i++
maxi = i

newlist.add((min(list[mini],u),max(list[maxi],u)) // add the new interval

while (i < list.length) // add remaining intervals
  newlist.add(list[i++])

return newlist