Algorithm to calculate number of intersecting discs

前端 未结 30 1518
鱼传尺愫
鱼传尺愫 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:54

    A Python answer

    from bisect import bisect_right
    
    def number_of_disc_intersections(li):
        pairs = 0
        # treat as a series of intervals on the y axis at x=0
        intervals = sorted( [(i-li[i], i+li[i]) for i in range(len(li))] )
        # do this by creating a list of start points of each interval
        starts = [i[0] for i in intervals]
        for i in range(len(starts)):
            # find the index of the rightmost value less than or equal to the interval-end
            count = bisect_right(starts, intervals[i][1])
            # subtract current position to exclude previous matches, and subtract self
            count -= (i+1)
            pairs += count
            if pairs > 10000000:
                return -1
        return pairs
    

提交回复
热议问题