【发布时间】:2022-08-18 21:43:40
【问题描述】:
我有一个在图表上代表 X、Y 的项目列表(都从点 (0,0) 开始。 例子:
1. [(0,0),(0,1),(0,2),(1,2),(2,2)]
2. [(0,0),(0,1),(0,2),(1,2),(2,2),(2,1),(1,1),(0,1)]
第 2 项无效,因为它与点 (0,1) 相交。
为了查找是否存在交集,我对列表进行排序(nlogn)并迭代以查找 2 个点是否相同。
def is_intersect(points ):
# points [(0,0)...]
points.sort()
for m,u in zip(points,points[1:]):
if m==u:
return True
return False
我的问题: 有没有比上述算法更好的方法来找到交集(空间复杂度 O(1) 没有额外的集合或哈希集)?
-
@trincot这不是重复的,因为OP特别要求空间复杂度为O(1).
-
所以一个“相交”列表只是一个包含相同点两次或更多的列表?我认为您可能是指时间复杂度而不是空间复杂度? Space complexity of python sort is O(n) or best case O(1)
-
我更新了帖子。不使用额外的集合或哈希集
-
@pylos 请注意,您自己的代码确实使用了额外的空间,因为
sorted会复制数组。如果您想在不使用额外空间的情况下就地排序,请使用points.sort()而不是p = sorted(points)。
标签: python algorithm sorting optimization