Given a set of intervals, find how many intervals contain a point

前端 未结 3 681
小鲜肉
小鲜肉 2021-01-16 15:54

Suppose you are given a set of N intervals (represented as left and right coordinates) and M points. For each point P algorithm should find number of intervals to which P be

3条回答
  •  没有蜡笔的小新
    2021-01-16 16:36

    If you sort the set of interval endpoints (both left and right endpoints together), and then process the interval endpoints from left to right (keeping track of what intervals they belong to), then in between each pair of consecutive endpoints you can record the number of intervals that overlap that subinterval in between the two endpoints (increasing the count by +1 every time you encounter a left-endpoint, and decreasing the count by -1 every time you encounter a right-endpoint). Then, given a query point, you just do binary search into the array of endpoints to find the two endpoints whose subinterval contains the query point, and report the number of intervals you previously computed that contain the subinterval. For N intervals and P query points total run time is O(N log N + P log N). Storage is O(N).

提交回复
热议问题