How to count the presence of a set of numbers in a set of intervals efficiently

前端 未结 3 1027
半阙折子戏
半阙折子戏 2021-01-05 11:50

The input parameters are a list of tuples representing the intervals and a list of integers. The goal is to write a function that counts the number of intervals each integer

3条回答
  •  长发绾君心
    2021-01-05 12:42

    You can presort the integers and then use bisect_left on the lower bound. Sorting has O(M*log(M)) complexity while bisect has O(log(M)). So effectively you have O(max(M, N) * log(M)).

    import bisect
    from collections import defaultdict
    
    result = defaultdict(int)
    integers = sorted(integers)
    for low, high in intervals:
        index = bisect.bisect_left(integers, low)
        while index < len(integers) and integers[index] <= high:
            result[integers[index]] += 1
            index += 1
    

提交回复
热议问题