这是一个简单的算法来做你所要求的,并且只在你的数据集中循环一次。
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSArray *booksAndTitles = @[
@[@"Book A1", @"Author A"],
@[@"Book B" , @"Author B"],
@[@"Book C" , @"Author C"],
@[@"Book A2", @"Author A"],
@[@"Book A3", @"Author A"],
@[@"Book C" , @"Author C"],
@[@"Book B" , @"Author B"]
];
NSMutableDictionary *titlesByAuthor = [NSMutableDictionary dictionary];
for (NSArray *pair in booksAndTitles) {
NSString *title = pair[0];
NSString *author = pair[1];
NSMutableArray *titles = titlesByAuthor[author];
if (titles == nil) {
titles = [NSMutableArray array];
titlesByAuthor[author] = titles;
}
[titles addObject:title];
}
NSLog(@"%@",titlesByAuthor);
}
return 0;
}
输出如下:
{
"Author A" = (
"Book A1",
"Book A2",
"Book A3"
);
"Author B" = (
"Book B",
"Book B"
);
"Author C" = (
"Book C",
"Book C"
);
}