ruby - Is this kata solution considered O(n)?
问题描述
I have the following solution to a kata:
def commonalities(array1, array2)
in_common = false
array1.each do |elem|
if array2.include?(elem)
in_common = true
break
end
end
puts in_common
end
##### Problem: Should find common elements in an array
array1 = ['a','b','c','x']
array2 = ['z','y','i']
commonalities(array1, array2)
# return false
array1 = ['a','b','c','x']
array2 = ['z','y','x']
# return true
commonalities(array1, array2)
I'm relearning BigO notation and doing some job interview katas. From what I've learned so far, I would say that this implementation is O(n) notation which is considered "fair". Is this a correct assumption? I say that this is O(n) because I have one loop, the .each
. The bigger the array gets the longer it would take. This to me implies a linear O. However, the .include?
is throwing me off. I don't know how the internals of .include?
works. Does it even matter? Am I indeed correct to say that this is O(n)? Confirmation would be appreciated. Thanks.
解决方案
的内部实现.include?
确实很重要,因为它可能是另一个for
或each
循环,因此更接近 O( mn )。
如果您知道例如 array1 保证是一个恒定大小,您可以说它是 O( n ),其中n是另一个数组的长度。然而,在这类问题中,我们通常假设两个数组的长度都是可变的,所以这个实现将被认为是 O( mn ),或者如果两个列表具有相同的长度,则被认为是 O( n2 ) 。
推荐阅读
- amazon-web-services - AWS Amplify、Next.js 和经过身份验证的 SSR 的问题
- sql - 甲骨文 SQL | 如果一列包含一个值,那么它将排除同一列中的不同值
- postgresql - 我们如何跟踪 postgreSQL 中逻辑复制的初始加载进度
- sql - 如何正确求和数据?
- arrays - 如何在 wordpress 过滤器中仅显示子类别?
- algorithm - 按升序排列对角矩阵
- azure - Azure devops 自动从部署组中删除目标虚拟机
- reactjs - 如何通过按 ENTER 键在反应待办事项应用程序中添加任务?
- flutter - 许可处理程序 - 位置不起作用(颤振)
- javascript - 如何通过axios获取请求/响应的总记录(X-Total-Count)?