我正在做演示文稿,比较不同语言的标准库的集合和算法。帮助我编写这个问题的有效且可读的算法:
元编程语言:
struct Tweet { id, time, text, url, user_id };
struct User { id, name, nick };
array<Tweet> tweets;
map<int, User> userDict;
问题:
找到发送最多推文且 url
字段不等于 nil
的用户名。
还可以找到来自该用户的此类推文的计数。
我是这样开始的:
NSMutableDictionary * countByUserId = [NSMutableDictionary dictionary];
foreach (Tweet * tweet in tweets)
if (tweet.url != 0)
countByUserId[tweet->user_id] = @(countByUserId[tweet->user_id] + 1);
现在我需要找到具有最大值的键值。
这是我的 C++ 代码:
map<int,int> countByUserId;
for (auto it = tweets.begin(); it != tweets.end(); ++it)
if (it->url != 0)
countByUserId[it->user_id]++;
auto para = max_element(countByUserId.begin(),
countByUserId.end(),
[](pair<int,int> a, pair<int,int> b)
{ return a.second < b.second; });
cout << "User = " << userDict[para.first].name << endl
<< "Value = " << para.second << endl;
最佳答案
Now I need to find key-value with max value...
可能存在联系,因此您应该查找所有具有最大值的键值对。您可以在循环中计算最大值,然后再次遍历 NSDictionary
,寻找它:
NSMutableDictionary * countByUserId = [NSMutableDictionary dictionary];
NSInteger max = -1;
foreach (Tweet * tweet in tweets) {
if (tweet.url != 0) {
int next = countByUserId[tweet->user_id].intValue + 1;
countByUserId[tweet->user_id] = @(next);
if (next > max) {
max = next;
}
}
}
[countByUserId enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj intValue] == max) {
NSLog(@"Found max for user: %@", key);
}
}
关于objective-c - 将 NSArray 中的元素映射到它们的计数并获得最频繁的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198189/