修改算法以查找 Maximum Number of Overlaps 以计算重叠数。
接近
算法复杂度为O(n*log(n))(来自排序)
代码
def overlap(v):
# variable to store the maximum
# count
ans = 0
count = 0
data = []
# storing the x and y
# coordinates in data vector
for i in range(len(v)):
# pushing the x coordinate
data.append([v[i][0], 'x'])
# pushing the y coordinate
data.append([v[i][1], 'y'])
# sorting of ranges
data = sorted(data)
# Traverse the data vector to
# count number of overlaps
for i in range(len(data)):
# if x occur it means a new range
# is added so we increase count
if (data[i][1] == 'x'):
count += 1
if count > 1:
ans += (count - 1) # new range intersets
# count - 1 existing
# ranges
# if y occur it means a range
# is ended so we decrease count
if (data[i][1] == 'y'):
count -= 1
# Return number of overlaps
return ans
测试
v = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]
print(overlap(v)) # Output 2
v = [[1,5], [3,7], [9,11], [6,8]]
print(overlap(v)) # Output 2
v = [[1,5], [3,7], [9,11], [6,8], [1, 11]]
print(overlap(v)) # Output 6
v = [ [ 1, 3 ], [ 2, 7 ], [3, 5], [4, 6] ]
print(overlap(v)) # Output 5