Fastest way to check if an array contains the same objects of another array

后端 未结 10 1897
夕颜
夕颜 2020-12-29 04:36

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

10条回答
  •  一向
    一向 (楼主)
    2020-12-29 05:05

    If you want to check whether both arrays contain the same duplicates, just use NSCountedSet. It's like an NSSet, but each object in the set also has a count telling you how often it has been added. So

    BOOL same = (array1.count == array2.count);
    if (same && array.count > 0)
    {
        NSCountedSet* set1 = [[NSCountedSet alloc] initWithArray:array1];
        NSCountedSet* set2 = [[NSCountedSet alloc] initWithArray:array2];
        same = ([set1 isEqual: set2]);
    }
    

    No matter how you do it, this will be time consuming, so you might consider if there are special cases that can be handled quicker. Are these arrays usually the same, or almost the same, or is it true 99% of the time that they are different and that 99% of the time a random element of array1 is not in array2? Are the arrays often sorted? In that case, you could check whether there are identical objects in identical positions, and then consider only those objects that are not the same. If one array contains objects a, b, c, d, e and the other contains a, b, x, d, y, then you only need to compare the array [c, e] vs. [x, y].

提交回复
热议问题