What's a good, generic algorithm for collapsing a set of potentially-overlapping ranges?

后端 未结 10 2018
执念已碎
执念已碎 2020-12-08 00:28

I have a method that gets a number of objects of this class

class Range
{
    public T Start;
    public T End;
}

In my case

10条回答
  •  北海茫月
    2020-12-08 01:09

    A Python solution for the non-verbosephile:

    ranges = [
      (11, 15),
      (3, 9),
      (12, 14),
      (13, 20),
      (1, 5)]
    
    result = []
    cur = None
    for start, stop in sorted(ranges): # sorts by start
      if cur is None:
        cur = (start, stop)
        continue
      cStart, cStop = cur
      if start <= cStop:
        cur = (cStart, max(stop, cStop))
      else:
        result.append(cur)
        cur = (start, stop)
    result.append(cur)
    
    print result
    

提交回复
热议问题