Geo*_*kos 6 algorithm objective-c set
我最近不得不解决以下算法问题,这让我很困惑.
假设您有一组包含整数的集合.编写一个函数,返回所有集合,其中所有集合都不在任何其他集合中.
例{0,4,9},{3,4,5},{6,7,8}
结果{6,7,8}
代码应该是Objective-C或Swift.
[编辑]
到目前为止,我出现了类似的东西,但无法真正完成它.
- (NSArray*) getDisjointedSets:(NSArray*)sets {
NSArray* resultedSet;
NSMutableArray* indexDoesntExistInSets = [NSMutableArray array];
[sets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSArray* nextIndexArray = [sets objectAtIndex:idx+1];
NSNumber* numberIndex = obj;
[nextIndexArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSNumber* numberNextIndex = obj;
if (numberIndex.intValue == numberNextIndex.intValue) {
// number exists in the next set, continue
*stop = YES;;
} else {
[indexDoesntExistInSets addObject:numberIndex];
}
}];
}];
return resultedSet;
}
Run Code Online (Sandbox Code Playgroud)
您的代码迭代数组的数组。但是然后你得到下一个数组,迭代它的数字,但尝试将每个数字与当前集合进行比较。
假设你有一个NSArrayofNSArray对象,你可以这样做:
- (NSArray *)getDisjointedSets:(NSArray *)sets {
NSMutableArray *resultSet = [NSMutableArray array];
for (NSArray *arrayA in sets) {
BOOL noMatch = YES;
for (NSArray *arrayB in sets) {
// Skip if both are the same array
if (arrayA != arrayB) {
NSMutableSet *setA = [NSMutableSet setWithArray:arrayA];
NSSet *setB = [NSSet setWithArray:arrayB];
[setA intersectSet:setB];
if (setA.count) {
// The two sets have something in common
noMatch = NO;
break;
}
}
}
if (noMatch) {
[resultSet addObject:arrayA];
}
}
return resultSet;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
NSArray *sets = @[
@[ @0, @4, @9 ],
@[ @3, @4, @5 ],
@[ @6, @7, @8 ]
];
NSArray *result = [self getDisjointedSets:sets];
NSLog(@"results = %@", result);
Run Code Online (Sandbox Code Playgroud)