Finding (number of) overlaps in a list of time ranges

后端 未结 9 650
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 19:53

Given a list of time ranges, I need to find the maximum number of overlaps.

Following is a dataset showing a 10 minute interval of calls, from which I am trying to f

9条回答
  •  盖世英雄少女心
    2020-12-04 20:19

    I think an important element of good solution for this problem is to recognize that each end time is >= the call's start time and that the start times are ordered. So rather than thinking in terms of reading the whole list and sorting we only need to read in order of start time and merge from a min-heap of the end times. This also addresses the comment Sanjeev made about how ends should be processed before starts when they have the exact same time value by polling from the end time min-heap and choosing it when it's value is <= the next start time.

    max_calls = 0
    // A min-heap will typically do the least amount of sorting needed here.
    // It's size tells us the # of currently active calls.
    // Note that multiple keys with the same value must be supported.
    end_times = new MinHeap()
    for call in calls:
      end_times.add(call.end)
      while (end_times.min_key() <= call.start) {
        end_times.remove_min()
      }
      // Check size after calls have ended so that a start at the same time
      // doesn't count as an additional call.  
      // Also handles zero duration calls as not counting.
      if (end_times.size() > max_calls) max_calls = end_times.size()
    }
    

提交回复
热议问题