5

我有一个充满字符串的数组,每个字符串都是一个名称。有些名称可能相同,而有些名称可能不同。我正在使用的语言是objective-C。我希望能够从该数组中找出最受欢迎的名称(该数组将根据用户提供给应用程序的信息是动态的)。我不确定如何有效地做到这一点。如果有人可以对此进行扩展或提供示例,将不胜感激。

谢谢

例子:

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; 

  //james would be the most popular name
4

3 回答 3

11

使用NSCountedSet然后使用 countForObject:方法找到计数最高的对象。

//create count set from array
NSCountedSet *setOfObjects = [[NSCountedSet alloc] initWithArray:yourArrayhere];

//Declaration of objects
NSString *mostOccurringObject = @"";
NSUInteger highestCount = 0;

//Iterate in set to find highest count for a object
for (NSString *strObject in setOfObjects)
{
    NSUInteger tempCount = [setOfObjects countForObject:strObject];
    if (tempCount > highest)
    {
        highestCount = tempCount;
        mostOccurringObject = strObject;
    }
}

检查结果:

NSLog(@"Most frequent string: %@ with count: %i", mostOccurringObject,highestCount);

归功于@Evan Mulawski的回答

于 2012-09-01T10:32:54.243 回答
5

我会使用一个哈希表(NSMutableDictionary在你的情况下),遍历字符串数组,使用每个字符串作为键,并将其值设置为它在数组中出现的次数。您可以使用变量(或名称数组,如果有多个名称具有相同的出现次数)来跟踪最大值。

然后运行时间是线性的( O(n) 其中 n 是数组中名称的数量)。

于 2012-09-01T10:37:51.213 回答
0

获取出现次数。

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; 
NSCountedSet *set = [[NSCountedSet alloc] nameArray];
于 2017-02-28T14:23:45.443 回答