数组包含来自另一个数组的任何值? [英] Array include any value from another array?

查看:30
本文介绍了数组包含来自另一个数组的任何值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于数组包含来自另一个数组的任何值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆