我有两个数组,但它们的长度不同。我想比较这两个数组并将共同项放入一个新数组。同时,should not have duplicate items 是第三个数组。 我真的搞砸了,请帮帮我。 非常感谢。 . .
最佳答案
是这样的吗?
NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the objects that are in both sets
NSArray* result = [set1 allObjects];
这样做的好处是不用查找数组中的对象,同时循环遍历另一个数组,复杂度为 N^2,如果数组很大,可能需要一段时间。
编辑:set2 不必是可变的,不妨使用
NSSet* set2 = [NSSet setWithArray:array2];
关于iphone - 比较两个数组并获取共同项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7246273/