Sub O(n^2) algorithm for counting nested intervals?

前端 未结 2 1029
误落风尘
误落风尘 2020-12-10 05:23

We have a list of intervals of the form [ai, bi]. For each interval, we want to count the number of other intervals that are nested withi

2条回答
  •  遥遥无期
    2020-12-10 05:46

    Here is a O(N*LOG(N)):

    let Ii = Interval i = (ai, bi)

    let L = list of intervals I

    sort L by ai

    divide L in half into L1a and L2a.

    sort L1a and L2a by bi to get L1b and L2b

    merge sort L1b and L2b keeping track of the count of nestings (e.g. because all intervals in L1b start before intervals in L2b, when we find an endpoint in L1b that is higher than an endpoint in l2b, we know everything between them is nested inside - think about it)..

    Now you have updated the counts on how often an interval in L2 is nested inside an interval in L1.

    after merging L1 and L2, we repeat the process (recursion) by dividing L1 into L11a and l12a, also dividing L2 into L21a and L21a..

提交回复
热议问题