比较两个数组并获得常用项 [英] compare two arrays and get the common items

查看:77
本文介绍了比较两个数组并获得常用项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,但它们有不同的长度。我想比较这两个数组和将常用项目放到新数组。同时不应该有重复项是第三个数组。
我真的搞砸了这个,请给我一个帮助。
非常感谢。 。 。

I have two arrays, but they have different lengths. I want to compare these two arrays and put common items to a new array. meanwhile there should not be have duplicate items is the third array. I really mess up with this, please give me a help. highly thankful . . .

推荐答案

这样的事情?

NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];

这样做的好处是不会查找数组中的对象,同时循环遍历另一个数组,具有N ^ 2的复杂性,如果数组很大,可能需要一段时间。

This has the benefit of not looking up the objects in the array, while looping through another array, which has N^2 complexity and may take a while if the arrays are large.

编辑:set2不必是可变的,也可以只使用

set2 doesn't have to be mutable, might as well use just

NSSet* set2 = [NSSet setWithArray:array2];

这篇关于比较两个数组并获得常用项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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