本文介绍了如何检查一个数组是否包含另一个数组的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查一个数组是否包含另一个数组的值.例如,我想检查数组A是否包含来自数组B的值.
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.
我正在寻找任何值,而不是一个特定值.
I'm looking for any value not one specific value.
推荐答案
如果要查看两个数组之间是否有任何重叠,可以执行以下操作:
If you're wanting to see if there is any overlap at all between two arrays, you can do this:
fun Array<*>.intersects(other: Array<*>) = any { it in other }
如下面的评论中所述,这是O(n ^ 2),因此对于大型数组,建议:
As mentioned in the comments below, this is O(n^2) so with large arrays, prefer:
fun Array<*>.intersects(other: Array<*>) = intersect(other.toSet()).isNotEmpty()
仅当第二个集合是数组而不是类似List的Iterable时,才需要
toSet()
.
toSet()
is only needed if the second collection is an Array rather than an Iterable like List.
这篇关于如何检查一个数组是否包含另一个数组的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!