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

后端 未结 10 1839
夕颜
夕颜 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:22

    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.

    Ex:

    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");
    }
    
    0 讨论(0)
  • 2020-12-29 05:24

    This way the complexity is O(N^2), if you follow this approach you can't do it with a lower complexity. While instead you can do it with O(N log(N)) if you sort both arrays and then compare them. This way after having them sorted you will do it using isEqualToArray: in other N operations.

    0 讨论(0)
  • 2020-12-29 05:27

    I know it's late but i just wanna share what i did..

    NSString *stringArr1 = [NSString stringWithFormat:@"%@", array1];
    NSString *stringArr2 = [NSString stringWithFormat:@"%@", array2];
    
    if ([stringArr1 isEqual: stringArr2])
        NSLog(@"identical");
    else
        NSLog(@"not");
    

    this is just like comparing "@[@1,@2,@3,@4]" == "[@3,@2,@1,@4]".. which is obviously false..

    0 讨论(0)
  • 2020-12-29 05:30

    Tried to get the accepted answer working but it wasn't quite the best fit for my situation.

    I found this answer and all credit goes to @joel kravets for the method.

    Basically sorting using a comparator enables you to sort using objects more easily - hence the problem I was facing when trying to use the above solution.

    NSArray * array1 = [NSArray arrayWithArray:users];
    NSArray * array2 = [NSArray arrayWithArray:threadUsers];
    
    id mySort = ^(BUser * user1, BUser * user2){
        return [user1.name compare:user2.name];
    };
    
    array1 = [array1 sortedArrayUsingComparator:mySort];
    array2 = [array2 sortedArrayUsingComparator:mySort];
    
    if ([array1 isEqualToArray:array2]) {
        NSLog(@"both are same");
    }
    else{
        NSLog(@"both are different");
    }
    

    Previously I had tried to use other answers like those above, using break to go through loops but in the end this answer came out easiest probably due to its speed and also that in the end we have the if statement allowing us to put code depending on if they are the same or different.

    Thanks to Anoop for getting me on the right track and Joel for helping me to tighten the efficiency of it

    0 讨论(0)
提交回复
热议问题