检查数组是否包含另一个数组的相同对象的最快方法 [英] Fastest way to check if an array contains the same objects of another array

查看:136
本文介绍了检查数组是否包含另一个数组的相同对象的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是比较两个数组并检查它们是否包含相同的对象(尽可能快 - 数组中有很多对象)。无法使用 isEqual:检查数组,因为它们的排序方式不同。

The goal is to compare two arrays as and check if they contain the same objects (as fast as possible - there are lots of objects in the arrays). The arrays cannot be checked with isEqual: as they are differently sorted.

我已尝试过此处发布的解决方案( https://stackoverflow.com/a/1138417 - 请参阅Peter Hosey发布的帖子的最后一个代码段。但这不适用于不同排序的数组。

I already tried the solution posted here (https://stackoverflow.com/a/1138417 - see last code snippet of the post by Peter Hosey). But this doesn't work with differently sorted arrays.

我现在使用的代码如下:

The code I'm using now is the following:

+ (BOOL)arraysContainSameObjects:(NSArray *)array1 andOtherArray:(NSArray *)array2 {
    // quit if array count is different
    if ([array1 count] != [array2 count]) return NO;

    BOOL bothArraysContainTheSameObjects = YES;
    for (id objectInArray1 in array1) {
        BOOL objectFoundInArray2 = NO;
        for (id objectInArray2 in array2) {
            if ([objectInArray1 isEqual:objectInArray2]) {
                objectFoundInArray2 = YES;
                break;
            }
        }
        if (!objectFoundInArray2) {
            bothArraysContainTheSameObjects = NO;
            break;
        }
    }

    return bothArraysContainTheSameObjects;
}

这是有效的,但这是两个嵌套的快速枚举。有没有办法进行更快的比较?

This works, but those are two nested fast enumerations. Is there a way to do a faster comparison?

推荐答案

根据您的代码,您对相同数量的元素和每个元素都是严格的第一个数组的对象应该在第二个数组中,反之亦然。

As per your code, you are strict to same number of elements and each object of first array should be there in second array and vice versa.

最快的方法是对数组进行排序并比较它们。

The fastest way would be to sort both the array and compare them.

前:

NSArray *array1=@[@"a",@"b",@"c"];
NSArray *array2=@[@"c",@"b",@"a"];

array1=[array1 sortedArrayUsingSelector:@selector(compare:)];
array2=[array2 sortedArrayUsingSelector:@selector(compare:)];

if ([array1 isEqualToArray:array2]) {
    NSLog(@"both have same elements");
}
else{
    NSLog(@"both having different elements");
}

这篇关于检查数组是否包含另一个数组的相同对象的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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