数组是否包含来自另一个数组的任何值? [英] Array include any value from another array?
问题描述
测试数组是否包含第二个数组中的任何元素的最有效方法是什么?
What's the most efficient way to test if an array contains any element from a second array?
下面的两个示例试图回答这个问题,foods
是否包含cheeses
中的任何元素:
Two examples below, attempting to answer the question does foods
contain any element from cheeses
:
cheeses = %w(chedder stilton brie mozzarella feta haloumi reblochon)
foods = %w(pizza feta foods bread biscuits yoghurt bacon)
puts cheeses.collect{|c| foods.include?(c)}.include?(true)
puts (cheeses - foods).size < cheeses.size
推荐答案
(cheeses & foods).empty?
正如Marc-AndréLafortune在评论中说的那样,&
在线性时间内起作用,而any?
+ include?
将是平方的.对于更大的数据集,线性时间会更快.对于小型数据集,如Lee Jarvis的回答所示,any?
+ include?
可能更快-可能是因为&
分配了一个新的Array,而另一种解决方案却没有,并且它只是一个简单的嵌套循环以返回布尔值.
As Marc-André Lafortune said in comments, &
works in linear time while any?
+ include?
will be quadratic. For larger sets of data, linear time will be faster. For small data sets, any?
+ include?
may be faster as shown by Lee Jarvis' answer -- probably because &
allocates a new Array while another solution does not and works as a simple nested loop to return a boolean.
这篇关于数组是否包含来自另一个数组的任何值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!