我最近不得不解决以下算法问题,这让我很困惑。
假设您有一组包含整数的集合。写一个 函数返回其中所有数字都不在其中的所有集合 另一套。
示例{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;
}
答案 0 :(得分:0)
您的代码会迭代数组数组。但是接着你得到下一个数组,迭代它的数字,但试着将每个数字与当前数据进行比较。
假设你有NSArray
个NSArray
个对象,你可以这样做:
- (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;
}
测试代码:
NSArray *sets = @[
@[ @0, @4, @9 ],
@[ @3, @4, @5 ],
@[ @6, @7, @8 ]
];
NSArray *result = [self getDisjointedSets:sets];
NSLog(@"results = %@", result);