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

后端 未结 10 1940
夕颜
夕颜 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");
    }
    

提交回复
热议问题