检查一个区域是否与另一个1-d区域重叠的快速方法

问题描述

|| 我有很多地区,从起点到终点都有数千个点。即: [(3015,3701),(4011,5890),....] 我还有另一组点(开始和结束),在这些点上,我需要一种快速方法来测试该组中的区域是否与另一组中的区域重叠。有快速方法吗? 谢谢! - 编辑 - @Spike Gronim用间隔树回答了我的问题。 谢谢,斯派克! http://en.wikipedia.org/wiki/Interval_tree     

解决方法

def test(lista,listb):
    a = 0
    b = 0
    found = False
    while a<len(lista) and b<len(listb):
        result = check( lista[a],listb[b] )
        if result < 0:
            a += 1
            continue
        if result > 0:
            b += 1
            continue
        # we found overlapping intervals
        found = True
        return (found,a,lista[a],b,listb[b] )
    return found

def check( (astart,aend),(bstart,bend) ):
    if aend < bstart:
        return -1
    if bend < astart:
        return 1
    return 0


lista = [(3015,3701),(4011,5890)]
listb = [(1,2),(100,200),(4500,6000)]
result = test(lista,listb)
print result
    ,找到两个区域的最小/最大端点,然后查看它们是否重叠。