数组包含来自另一个数组的任何值?

数组包含来自另一个数组的任何值?

问题描述:

测试一个数组是否包含来自第二个数组的任何元素的最有效方法是什么?

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? 将是二次的.对于较大的数据集,线性时间会更快.对于小数据集,any? + include? 可能更快,如 Lee Jarvis 的回答所示——可能是因为 & 分配了一个新的数组,而另一种解决方案没有,它作为一个简单的嵌套循环返回一个布尔值.

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.