Ale*_*x G 5 xcode objective-c nsarray ios
我有一个充满字符串的数组,每个字符串都是一个名字.有些名称可能相同,有些名称可能不同.我正在使用的语言是Objective-C.我希望能够从这个数组中找出最受欢迎的名称(该数组将根据用户提供给应用程序的信息而动态显示).我不确定如何有效地实现这一目标.如果有人可以扩展或提供一个例子,我们将不胜感激.
谢谢
例:
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil];
//james would be the most popular name
Run Code Online (Sandbox Code Playgroud)
Par*_*iya 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;
}
}
Run Code Online (Sandbox Code Playgroud)
检查结果:
NSLog(@"Most frequent string: %@ with count: %i", mostOccurringObject,highestCount);
Run Code Online (Sandbox Code Playgroud)
信用去@Evan Mulawski答案
我将使用哈希表(NSMutableDictionary在您的情况下),遍历字符串数组,使用每个字符串作为键,并将其值设置为它在数组中出现的数字.您可以使用变量(或多个名称具有相同出现次数的名称数组)跟踪最大值.
然后运行时间是线性的(O(n),其中n是数组中的名称数).
| 归档时间: |
|
| 查看次数: |
3492 次 |
| 最近记录: |