我有一个数组满了每个字符串是一个名称的字符串。 有些名字可能是相同的,而有些人可能会有所不同。 我的工作语言是客观-C。 我希望能够找出其中的名字是从这个阵列(阵列将基于从用户给出了应用信息是动态的)最流行的。 我不知道如何使这有效地发生。 如果有人可以扩大这或提供一个例子,我们将不胜感激。
谢谢
例:
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil];
//james would be the most popular name
使用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答案
我会用一个哈希表( NSMutableDictionary
数组中你的情况),经过的字符串数组,使用每个字符串作为重点,并将其值设置为数字的出现。 你可以跟踪使用可变(或名称的数组如果存在具有相同数目的发生的多个名称)的最大的。
运行时间是线性然后(O(n),其中n是名称的数组中的数量)。
要获得出现的次数。
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil];
NSCountedSet *set = [[NSCountedSet alloc] nameArray];