iOS 数组集合操作(交集,并集,差集,子集)

求数组的 交集,并集,差集

NSArray *array1 = @[@"1",@"2",@"3"];
NSArray *array2 = @[@"1",@"5",@"6"]; 
NSMutableSet *set1 = [NSMutableSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2]; 
 
[set1 unionSet:set2];       //取并集后 set1中为1,2,3,5,6
[set1 intersectSet:set2];  //取交集后 set1中为1
[set1 minusSet:set2];      //取差集后 set1中为2,3,5,6

判断一个数组是否为另一个数组的子集

NSArray *array3 = @[@"1",@"2"];
NSArray *array4 = @[@"1",@"2",@"6"];
NSSet *set3 = [NSSet setWithArray:array3];
NSSet *set4 = [NSSet setWithArray:array4];
 
BOOL isSub = [set3 isSubsetOfSet:set4];     //isSub为YES

判断某个对象是否在某个数组中

BOOL isExist = [array3 containsObject:@"1"]; //isExist为YES

你可能感兴趣的:(iOS 数组集合操作(交集,并集,差集,子集))