[英]Time complexity of finding range of target in sorted array - Is this solution O(N) in the worst case?
[英]why is the worst case time complexity of this algorithm O(n)?
下面的算法不应该是 O(n^2) 最坏的情况吗? 因为我们首先迭代数组中的 n 个元素,那么在最坏的情况下,数组恰好只包含不同的元素,所以当我们检查 Set 是否存在元素时,我们必须在之前再次迭代 n 个元素添加该元素,所以O(n ^ 2)?
# This function prints all distinct elements
def countDistinct(arr, n):
# Creates an empty hashset
s = set()
# Traverse the input array
res = 0
for i in range(n):
# If not present, then put it in
# hashtable and increment result
if (arr[i] not in s):
s.add(arr[i])
res += 1
return res
# Driver code
arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]
n = len(arr)
print(countDistinct(arr, n))
您是对的,集合查找的最坏情况时间复杂度是 O(n),并且您已经正确描述了发生这种情况的场景。 如果集合中的每个元素都相同,则不会有任何 hash 冲突,这将保证 O(1) 集合成员资格检查和整个 O(n) 运行时仅插入一次。 如果在每次成员资格检查/插入期间每个元素都是不同的并且与集合中的每个键发生冲突,那将导致 O(n) 添加/查找,这将是 O(n^2) 复杂度。
我认为您的结论是正确的,但推理并不完全正确:
在添加该元素之前,我们必须再次迭代 n 个元素
这不是必需的。 在 CPython 中,集合被实现为 hash 表而不是链表(或其他必须需要O(n)
时间到 append 元素的结构)。 只有当发生严重的 hash 碰撞时(例如所有值不同但它们的 hash 值相同),添加元素的时间复杂度才能达到O(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.