在数组中find最重复的对象
我有一个数组,每个string都是一个名字。 有些名字可能是相同的,有些可能会有所不同。 我正在使用的语言是客观的C语言。 我希望能够从这个数组中找出哪个名字是最受欢迎的(该数组将根据从用户提供给应用程序的信息进行dynamic变化)。 我不知道如何有效地做到这一点。 如果有人可以扩大或提供一个例子,这将不胜感激。
谢谢
例:
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; //james would be the most popular name
使用NSCountedSet
,然后使用countForObject:
方法find具有最高计数的对象。
//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
在你的情况),通过string数组,使用每个string作为关键,并将其值设置为其在数组中出现的数字。 您可以使用variables(或者如果有多个名称具有相同的出现次数的名称数组)来跟踪最大值。
运行时间是线性的(O(n),其中n是数组中的名称数)。
获取发生的次数。
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; NSCountedSet *set = [[NSCountedSet alloc] nameArray];