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

后端 未结 10 1924
夕颜
夕颜 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条回答
  •  猫巷女王i
    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

提交回复
热议问题