Algorithm to calculate number of intersecting discs

前端 未结 30 1509
鱼传尺愫
鱼传尺愫 2020-12-12 10:57

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius

30条回答
  •  不思量自难忘°
    2020-12-12 11:39

    So you want to find the number of intersections of the intervals [i-A[i], i+A[i]].

    Maintain a sorted array (call it X) containing the i-A[i] (also have some extra space which has the value i+A[i] in there).

    Now walk the array X, starting at the leftmost interval (i.e smallest i-A[i]).

    For the current interval, do a binary search to see where the right end point of the interval (i.e. i+A[i]) will go (called the rank). Now you know that it intersects all the elements to the left.

    Increment a counter with the rank and subtract current position (assuming one indexed) as we don't want to double count intervals and self intersections.

    O(nlogn) time, O(n) space.

提交回复
热议问题